使用 DataContractSerializer 时遇到问题
我在使用 DataContractSerializer 序列化不可变实例时遇到问题,因为我正在序列化的类的属性缺少设置器。问题是我只想序列化实例(只是为了将其写入日志),并且我永远不需要反序列化它。有没有办法绕过这种行为?
我试图序列化的类:
[DataContract]
public class Person
{
private readonly string _name;
[DataMember]
public string Name
{
get { return _name; }
}
public Person(string name)
{
_name = name;
}
}
用于序列化该类的代码:
public string Serialize()
{
var serializer = new DataContractSerializer(typeof(Person));
StringBuilder stringBuilder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(stringBuilder)) {
serializer.WriteObject(writer, this);
}
return stringBuilder.ToString();
}
I'm having trouble serializing an immutable instance with the DataContractSerializer, since the properties on the class I'm serializing is missing setters. The problem is that I only want to serialize the instance (just so it can be written to a log), and I will never need to deserialize it. Is there a way to bypass this behavior?
The class I'm trying to serialize:
[DataContract]
public class Person
{
private readonly string _name;
[DataMember]
public string Name
{
get { return _name; }
}
public Person(string name)
{
_name = name;
}
}
The code used for serializing the class:
public string Serialize()
{
var serializer = new DataContractSerializer(typeof(Person));
StringBuilder stringBuilder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(stringBuilder)) {
serializer.WriteObject(writer, this);
}
return stringBuilder.ToString();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
[DataMember]
放在字段上,从而允许您拥有属性 getter。这些字段仍然可以是私有的。但是它不能是只读的,因为它需要构造对象然后设置字段。[编辑]
这将导致使用字段名称,除非您使用
[DataMember(Name = "Name1")]
You can place the
[DataMember]
on the fields thus allowing you to have property getters. These fields can still be private. However it cannot bereadonly
as it needs to construct the object then set the fields.[Edit]
This will cause the field names to be used unless you use
[DataMember(Name = "Name1")]
此版本使用 ISerialized 属性而不是 [DataContract]。
我不知道这将如何影响可操作性,但不需要公共设置器。
This version uses the ISerializable attribute instead of [DataContract].
I don't know how this will affect operability, but does not need a public setter.