我有一个没有设置TimeStamp的xml。我在这里尝试了所有可能的组合,但在反序列化时,它总是抛出异常:There was an error deserializing the object of type MyType. The value '' cannot be parsed as the type 'DateTime'.
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public DateTime TimeStamp = DateTime.Now;
我需要在此TImeStamp成员上设置什么,以便在反序列化时可选(=不需要在xml中)
编辑:我在Xaruth的建议中尝试过:[DataMember]
[DefaultValue(typeof(DateTime), "2014-08-25T09:31:09.2477328+02:00")]
public DateTime TimeStamp { get; set; }
public bool ShouldSerializeTimeStamp()
{
return TimeStamp != null;
}
public void ResetTimeStamp()
{
TimeStamp = DateTime.Now;
}
答案 0 :(得分:0)
您可以使用方法SouldSerialize
和Reset
,可以为任何属性定义。
对于名为TimeStamp
的属性,您可以编写方法SouldSerializeTimeStamp
和ResetTimeStamp
根据MSDN,ResetTimeStamp
会为您提供TimeStamp
的默认值,SouldSerializeTimeStamp
将用于序列化或不TimeStamp
。