使用 DataContractSerializer 时设置属性的初始值
如果我使用 DataContractSerializer 序列化并稍后反序列化一个类,如何控制未序列化的属性的初始值?
考虑下面的 Person
类。其数据协定设置为序列化 FirstName
和 LastName
属性,但不序列化 IsNew
属性。我希望 IsNew 初始化为 TRUE,无论新 Person 是被实例化为新实例还是从文件反序列化。
通过构造函数很容易做到这一点,但据我了解,DataContractSerializer 不会调用构造函数,因为它们可能需要参数。
[DataContract(Name="Person")]
public class Person
{
[DataMember(Name="FirstName")]
public string FirstName { get; set; }
[DataMember(Name = "LastName")]
public string LastName { get; set; }
public bool IsNew { get; set; }
public Person(string first, string last)
{
this.FirstName = first;
this.LastName = last;
this.IsNew = true;
}
}
If I am serializing and later deserializing a class using DataContractSerializer
how can I control the initial values of properties that were not serialized?
Consider the Person
class below. Its data contract is set to serialize the FirstName
and LastName
properties but not the IsNew
property. I want IsNew
to initialize to TRUE whether a new Person is being instantiate as a new instance or being deserialized from a file.
This is easy to do through the constructor, but as I understand it DataContractSerializer
does not call the constructor as they could require parameters.
[DataContract(Name="Person")]
public class Person
{
[DataMember(Name="FirstName")]
public string FirstName { get; set; }
[DataMember(Name = "LastName")]
public string LastName { get; set; }
public bool IsNew { get; set; }
public Person(string first, string last)
{
this.FirstName = first;
this.LastName = last;
this.IsNew = true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,正确的方法是使用 OnDeserializing 属性(注意“ing”后缀)。在反序列化成员值之前调用标有此属性的方法。
Actually the correct way of doing it is by using the OnDeserializing attribute (notice the "ing" suffix). The method marked with this attribute is called before the member values are deserialized.
您可以使用序列化回调。将以下方法添加到您的 Person 类中:
另一种选择是删除 [DataContract] 和 [DataMember] 属性。在这种情况下,DCSerializer 将在反序列化时调用您的构造函数。
You can use a serialization callback. Add the following method to your Person class:
Another option is to remove the [DataContract] and [DataMember] attributes. In this case DCSerializer will call your constructor when it deserializes.