在C# 4.0中序列化对象,有更简单的方法吗?
当设置一个对象进行序列化时,我会执行以下操作:
[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 中是否有更简单或更简洁的方法来执行此操作?
When set up an object for serialization I do the following:
[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);
}
}
It's quite exhausting when there are lots of properties. Is there a simpler or less verbose way of doing this in C# 4.0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除非您想要自定义序列化机制,否则不需要额外的构造函数或
GetObjectData
方法。如果您有简单的属性,默认的序列化机制将很好地处理它们。您所需要的只是Serialized
属性,然后您就万事大吉了。You don't need the extra constructor or the
GetObjectData
method unless you want to customize the serialization mechanism. If you have simple properties, the default serialization mechanism will handle them quite well. All you need is theSerializable
attribute, and you're golden.你为什么要手工做这个? BinaryFormatter 已经知道如何自动执行此操作。如果过滤字段很重要,那么创建另一个类来仅存储您想要序列化的字段。
Why are you doing this by hand? BinaryFormatter already knows how to do this automatically. If filtering the fields is important then make another class that just stores the ones that you want to serialize.
您还可以考虑使用
DataContract
序列化,这样可以在需要时轻松输出 JSON 或 XML。You could also consider using
DataContract
serialization which makes it easy to output JSON or XML if you ever need that.我想补充一点,由于您的类没有实现
ISerialized
,因此您的自定义GetObjectData
方法可能永远不会被调用。I'd like to add that since your class doesn't implement
ISerializable
, your customGetObjectData
method may never be called.