序列化私有成员数据 [英] Serializing private member data

查看:165
本文介绍了序列化私有成员数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化对象到XML有许多属性,其中一些是只读的。

 公众的Guid标识{获取;私定; }
 

我已经打上了阶级[可序列化],我已经实现了ISerializable接口。

下面是code我使用我的序列化对象。

 公共无效SaveMyObject(myObject的OBJ)
{
    XmlSerializer的序列化=新的XmlSerializer(typeof运算(为MyObject));
    TextWriter的TW =新的StreamWriter(_location);
    serializer.Serialize(TW,OBJ);
    tw.Close();
}
 

不幸的是它翻倒在与该消息的第一行。

  

InvalidOperationException异常是未处理的:   我们无法生成临时类(结果= 1)。   错误CS0200:属性或索引MyObject.Id'不能被分配​​到 - 它是只读的。

如果我的Id属性设置为公共它工作正常。谁能告诉我,如果我做的事情,或者至少它甚至可能吗?

解决方案

您可以使用的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 ,至少<。 / P>

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.

这篇关于序列化私有成员数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆