개인 멤버 데이터 직렬화
여러 속성이있는 XML로 개체를 직렬화하려고합니다. 그 중 일부는 읽기 전용입니다.
public Guid Id { get; private set; }
[Serializable] 클래스를 표시하고 ISerializable 인터페이스를 구현했습니다.
다음은 객체를 직렬화하는 데 사용하는 코드입니다.
public void SaveMyObject(MyObject obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
TextWriter tw = new StreamWriter(_location);
serializer.Serialize(tw, obj);
tw.Close();
}
불행히도이 메시지의 첫 번째 줄에 넘어갑니다.
InvalidOperationException이 처리되지 않았습니다. 임시 클래스를 생성 할 수 없습니다 (result = 1). 오류 CS0200 : 속성 또는 인덱서 'MyObject.Id'를 할당 할 수 없습니다. 읽기 전용입니다.
Id 속성을 public으로 설정하면 제대로 작동합니다. 누군가 내가 뭔가를하고 있는지 아니면 적어도 가능하다면 말해 줄 수 있나요?
다음을 사용할 수 있습니다 DataContractSerializer
(하지만 xml 속성은 사용할 수 없으며 xml 요소 만 사용할 수 있음).
using System;
using System.Runtime.Serialization;
using System.Xml;
[DataContract]
class MyObject {
public MyObject(Guid id) { this.id = id; }
[DataMember(Name="Id")]
private Guid id;
public Guid Id { get {return id;}}
}
static class Program {
static void Main() {
var ser = new DataContractSerializer(typeof(MyObject));
var obj = new MyObject(Guid.NewGuid());
using(XmlWriter xw = XmlWriter.Create(Console.Out)) {
ser.WriteObject(xw, obj);
}
}
}
또는 IXmlSerializable
모든 것을 직접 구현 하고 수행 할 수 있지만 XmlSerializer
최소한에서는 작동합니다 .
당신은을 사용할 수 있습니다 System.Runtime.Serialization.NetDataContractSerializer
. 더 강력하고 클래식 Xml Serializer의 일부 문제를 수정합니다.
이 속성에는 다른 속성이 있습니다.
[DataContract]
public class X
{
[DataMember]
public Guid Id { get; private set; }
}
NetDataContractSerializer serializer = new NetDataContractSerializer();
TextWriter tw = new StreamWriter(_location);
serializer.Serialize(tw, obj);
편집하다:
Marc의 의견을 기반으로 한 업데이트 : System.Runtime.Serialization.DataContractSerializer
깨끗한 XML을 얻으려면 사례에 사용해야 합니다. 나머지 코드는 동일합니다.
읽기 전용 필드는를 사용하여 직렬화되지 않습니다. XmlSerializer
이는 readonly
키워드 의 특성 때문입니다.
MSDN에서 :
The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
So... you would pretty much need to set the fields value in the default constructor...
Its not possible with that particular serialization mode (see the other comments for workarounds). If you really want to leave your serialization mode as-is, you have to work around the framework limitations on this one. See this example
Esentially, mark the property public
, but throw an exception if it's accessed at any time other than deserialization.
참고URL : https://stackoverflow.com/questions/802711/serializing-private-member-data
'Programing' 카테고리의 다른 글
Dockerfiles 또는 이미지 커밋을 사용해야합니까? (0) | 2020.10.25 |
---|---|
window.onload 대 body.onload 대 document.onready (0) | 2020.10.25 |
phonegap을 사용하여 바코드를 스캔하는 방법 (0) | 2020.10.25 |
SCRIPT7002 : XMLHttpRequest : 네트워크 오류 0x2ef3, 00002ef3 오류로 인해 작업을 완료 할 수 없습니다. (0) | 2020.10.25 |
웹 페이지 : 버전 설정의 기능은 무엇입니까? (0) | 2020.10.25 |