在C#4.0中序列化对象,有一种更简单的方法吗?

时间:2010-10-01 20:46:34

标签: c# serialization c#-4.0 object

设置序列化对象时,我会执行以下操作:

[Serializable]
public class ContentModel
{
    public int ContentId { get; set; }
    public string HeaderRendered { get; set; }

    public ContentModel()
    {
        ContentId = 0;
        HeaderRendered = string.Empty;
    }

    public ContentModel(SerializationInfo info, StreamingContext ctxt) 
    {
        ContentId = (int)info.GetValue("ContentId", typeof(int));
        HeaderRendered = (string)info.GetValue("HeaderRendered", typeof(string));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("ContentId ", ContentId);
        info.AddValue("HeaderRendered", HeaderRendered);
    }
}

当有很多房产时,这是非常令人疲惫的。在C#4.0中有更简单或更简洁的方法吗?

4 个答案:

答案 0 :(得分:11)

除非要自定义序列化机制,否则不需要额外的构造函数或GetObjectData方法。如果您有简单的属性,默认的序列化机制将很好地处理它们。您所需要的只是Serializable属性,而且您是金色的。

答案 1 :(得分:3)

你为什么这样做? BinaryFormatter已经知道如何自动执行此操作。如果过滤字段很重要,那么创建另一个只存储您要序列化的类。

答案 2 :(得分:2)

您还可以考虑使用DataContract序列化,这样可以在需要时轻松输出JSON或XML。

答案 3 :(得分:1)

我想补充一点,因为您的课程没有实施ISerializable,您的自定义GetObjectData方法可能永远不会被调用。

相关问题