【问题标题】:Serializing objects in C# 4.0, is there a simpler way?在 C# 4.0 中序列化对象,有没有更简单的方法?
【发布时间】:2011-04-20 01:36:01
【问题描述】:

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

[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 中有更简单或更简洁的方法吗?

【问题讨论】:

    标签: c# serialization c#-4.0 object


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您还可以考虑使用DataContract 序列化,如果您需要,它可以轻松输出 JSON 或 XML。

        【讨论】:

        • 这个。 DataContract 序列化器使普通案例序列化变得微不足道。
        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-11
          • 2021-03-24
          • 1970-01-01
          • 2011-10-06
          • 1970-01-01
          相关资源
          最近更新 更多