我不能使用XmlElementAttribute.序列化/反序列化中的IsNullable

本文关键字:反序列化 IsNullable 序列化 不能 XmlElementAttribute | 更新日期: 2023-09-27 18:04:11

这是我要序列化/反序列化的类

public class MyDic
{
    ...
    [XmlElement(IsNullable = true)]
    public List<WebDefinition> WebDefinitions;                      
    ...
}

,它是结构体WebDefinition的完整定义。

public struct WebDefinition
{
   public string Definition;
   public string URL;
   public WebDefinition(string def, string url)
   {
       Definition = def;
       URL = url;
   }
   public override string ToString() { return this.Definition; }
}

i期望Dictionary.WebDefinitions在反序列化时可以为空。但是当

出现运行时错误
//runtime error : System.InvalidOperationException
XmlSerializer myXml = new XmlSerializer(typeof(Dictionary), "UOC");

为什么我不能使用XmlElementAttribute.IsNullable ?

注一:

当我删除一行[XmlElement(IsNullable = true)]时,它工作正常,没有错误。(序列化和反序列化)。

注2:
例外是System。InvalidOperationException和消息是:"error occured in during reflection 'UOC.DicData' type"

谢谢。

我不能使用XmlElementAttribute.序列化/反序列化中的IsNullable

正如我在注释"特别是InnerException"中指出的;因为你没有添加这个,我运行了样本,最里面的InnerException是:

IsNullable may not be 'true' for value type WebDefinition. Please consider using Nullable<WebDefinition> instead.

我想这告诉了你你需要的一切。将其更改为WebDefinition?(即Nullable<WebDefinition>)确实可以解决此问题。

但这里的关键是:读取异常和InnerException .

在我看来,一个更好的"修复"是让它成为一个class;因为WebDefinition不是一个"值",所以它没有业务成为struct(特别是具有公共可变字段的结构体是……邪恶的):

public class WebDefinition
{
    public WebDefinition(){} // for XmlSerializer
    public string Definition { get; set; }
    public string URL { get; set; }
    public WebDefinition(string def, string url)
    {
       Definition = def;
       URL = url;
    }
    public override string ToString() { return this.Definition; }
}

如果你使用的是c# 4.0,你是否尝试过

public class MyDic
{
    ...
    public List<WebDefinition?> WebDefinitions;  //note the ? after your type.                    
    ...
}

哎呀,我想删除xelementnull部分。所以一个列表可以是空本身,所以我假设你正试图允许WebDefinition为空,以及。使用"?"将允许它为可空类型。它和你的属性做的差不多

你也可以用int来做这个…声明一个int,比如public int?myInt = null;它会起作用的。

http://msdn.microsoft.com/en-us/library/1t3y8s4s (v = vs.80) . aspx