且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

序列化私有成员数据

更新时间:2022-10-18 15:07:31

您可以使用的DataContractSerializer (但要注意不能使用XML属性 - 只有XML元素):

 使用系统;
使用System.Runtime.Serialization;
使用的System.Xml;
[DataContract]
类为MyObject {
    公众为MyObject(GUID ID){this.id = ID; }
    [数据成员(名称为ID)
    私人的Guid ID;
    公众的Guid ID为{{返回的id;}}
}
静态类节目{
    静态无效的主要(){
        VAR SER =新的DataContractSerializer(typeof运算(为MyObject));
        VAR OBJ =新的MyObject(Guid.NewGuid());
        使用(的XmlWriter XW = XmlWriter.Create(Console.Out)){
            ser.WriteObject(XW,OBJ);
        }
    }
}
 

另外,您也可以实现的IXmlSerializable ,并尽一切自己 - 而这一点也适用的XmlSerializer ,至少

I'm trying to serialize an object to XML that has a number of properties, some of which are readonly.

public Guid Id { get; private set; }

I have marked the class [Serializable] and I have implemented the ISerializable interface.

Below is the code I'm using to serialize my object.

public void SaveMyObject(MyObject obj)
{
    XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
    TextWriter tw = new StreamWriter(_location);
    serializer.Serialize(tw, obj);
    tw.Close();
}

Unfortunately it falls over on the first line with this message.

InvalidOperationException was unhandled: Unable to generate a temporary class (result=1). error CS0200: Property or indexer 'MyObject.Id' cannot be assigned to -- it is read only

If I set the Id property to public it works fine. Can someone tell me if I'm doing something, or at least if its even possible?

You could use DataContractSerializer (but note you can't use xml attributes - only xml elements):

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);
        }
    }
}

Alternatively, you can implement IXmlSerializable and do everything yourself - but this works with XmlSerializer, at least.