gpt4 book ai didi

c# - 将 Nullable 序列化为 XML

转载 作者:IT王子 更新时间:2023-10-29 04:04:12 27 4
gpt4 key购买 nike

我正在尝试序列化一个类,其中几个数据成员是 Nullable 对象,这是一个示例

[XmlAttribute("AccountExpirationDate")]
public Nullable<DateTime> AccountExpirationDate
{
get { return userPrincipal.AccountExpirationDate; }
set { userPrincipal.AccountExpirationDate = value; }
}

但是在运行时我得到了错误

Cannot serialize member 'AccountExpirationDate' of type System.Nullable`1[System.DateTime]. XmlAttribute/XmlText cannot be used to encode complex types.

不过我检查了一下,Nullable 是一个 SerializableAttribute .我做错了什么?

最佳答案

如果您只是想让它工作,那么也许:

using System;
using System.ComponentModel;
using System.Xml.Serialization;
public class Account
{
// your main property; TODO: your version
[XmlIgnore]
public Nullable<DateTime> AccountExpirationDate {get;set;}

// this is a shim property that we use to provide the serialization
[XmlAttribute("AccountExpirationDate")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public DateTime AccountExpirationDateSerialized
{
get {return AccountExpirationDate.Value;}
set {AccountExpirationDate = value;}
}

// and here we turn serialization of the value on/off per the value
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeAccountExpirationDateSerialized()
{
return AccountExpirationDate.HasValue;
}

// test it...
static void Main()
{
var ser = new XmlSerializer(typeof(Account));
var obj1 = new Account { AccountExpirationDate = DateTime.Today };
ser.Serialize(Console.Out, obj1);
Console.WriteLine();
var obj2 = new Account { AccountExpirationDate = null};
ser.Serialize(Console.Out, obj2);
}
}

这将仅在存在非空值时包含该属性。

关于c# - 将 Nullable<DateTime> 序列化为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2074240/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com