DataContract,默认 DataMember 值
有没有办法在反序列化期间选择不在 xml 文件中的属性的默认值?
如果 xml 文件中不存在 mAge
属性,我想使用默认值 18。这可能吗?
[DataContract]
public class Person
{
public Person ()
{
}
[DataMember(Name = "Name")]
public string mName { get; set; }
[DataMember(Name = "Age")]
public int mAge { get; set; }
[DataMember(Name = "Single")]
public bool mIsSingle { get; set; }
};
编辑以放置答案。
[DataContract]
public class Person
{
public Person ()
{
}
[DataMember(Name = "Name")]
public string mName { get; set; }
[DataMember(Name = "Age")]
public int? mAge { get; set; }
[DataMember(Name = "Single")]
public bool? mIsSingle { get; set; }
[System.Runtime.Serialization.OnDeserialized]
void OnDeserialized(System.Runtime.Serialization.StreamingContext c)
{
mAge = (mAge == null ? 18 : mAge); // 18 is the default value
}
}
Is there a way to choose default values of attributes that are not in the xml file during deserialization?
If the mAge
attribute is not present in the xml file, I want to use a default value of 18. Is it possible ?
[DataContract]
public class Person
{
public Person ()
{
}
[DataMember(Name = "Name")]
public string mName { get; set; }
[DataMember(Name = "Age")]
public int mAge { get; set; }
[DataMember(Name = "Single")]
public bool mIsSingle { get; set; }
};
Edit to put the answer.
[DataContract]
public class Person
{
public Person ()
{
}
[DataMember(Name = "Name")]
public string mName { get; set; }
[DataMember(Name = "Age")]
public int? mAge { get; set; }
[DataMember(Name = "Single")]
public bool? mIsSingle { get; set; }
[System.Runtime.Serialization.OnDeserialized]
void OnDeserialized(System.Runtime.Serialization.StreamingContext c)
{
mAge = (mAge == null ? 18 : mAge); // 18 is the default value
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用[OnDeserialized]
编辑:来自您的评论
对于 bool 或 int,您可以使用 可为空布尔值和可为空整数
因此,如果 xml 文件中缺少这些 Age 和 Single 属性,那么它们也将为 null。
这是我准备的快速样本
You can use [OnDeserialized]
EDIT: From your Comments
For bool or int you can use nullable bool and nullable int
so if these age and Single attributes are missing in xml file then they will be null as well.
here is quick sample I prepared
使用 [OnDeserializing()]
并且您在反序列化之前设置您的值。所以没有必要进行检查,这可能会出错——如果 mAge 被序列化为 0 怎么办?
use [OnDeserializing()]
and you set your values BEFORE the deserialization. So there is no check necessary, which could go wrong - what if the mAge was serialized to be 0?
这应该有效。
请查看此页面。
This should work.
Take a look at this page.