使用的DataContractSerializer时设置属性的初始值 [英] Setting the initial value of a property when using DataContractSerializer
问题描述
如果我是序列化和以后使用反序列化类的DataContractSerializer
我怎么能控制那些没有序列化属性的初始值?
考虑下面的<code>人类。它的数据契约设置序列化名字
和名字
属性,而不是 IsNew
属性。我想 IsNew
初始化为TRUE是否有新的人正在被实例化一个新的实例,或者被从文件中反序列化。
这是很容易做到通过构造函数,但据我所知它的DataContractSerializer
不调用构造函数,因为他们可能需要的参数。
[DataContract(名称为人)]
公共类Person
{
[数据成员(NAME =名字)
公共字符串名字{获得;组; }
[数据成员(名称为姓氏)
公共字符串名字{获得;组; }
公共BOOL IsNew {获得;组; }
公众人物(字符串第一个,最后一个字符串)
{
this.FirstName =第一;
this.LastName =最后;
this.IsNew = TRUE;
}
}
您可以使用序列化回调。添加下面的方法到您的Person类:
[OnDeserialized]
无效OnDeserialized(的StreamingContext上下文)
{
this.IsNew = TRUE;
}
另一种选择是去除[DataContract]和[数据成员]的属性。在这种情况下DCSerializer将调用构造函数时,反序列化。
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;
}
}
You can use a serialization callback. Add the following method to your Person class:
[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
this.IsNew = true;
}
Another option is to remove the [DataContract] and [DataMember] attributes. In this case DCSerializer will call your constructor when it deserializes.
这篇关于使用的DataContractSerializer时设置属性的初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!