这是我的序列化/反序列化的类。
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; }
}
我期望Dictionary.WebDefinitions
在反序列化时可以为空。但是在
//runtime error : System.InvalidOperationException
XmlSerializer myXml = new XmlSerializer(typeof(Dictionary), "UOC");
为什么我不能使用XmlElementAttribute.IsNullable
?
注1:
当我删除一行[XmlElement(IsNullable = true)]
时,它正常工作,没有错误。(序列化和反序列化)。
注2:
例外是System.InvalidOperationException,邮件是:"error occured in during reflection 'UOC.DicData' type"
感谢。
答案 0 :(得分:6)
正如我在评论中指出的那样“特别是InnerException”;因为你没有添加这个,我运行了样本,最里面的InnerException
是:
IsNullable may not be 'true' for value type WebDefinition. Please consider using Nullable<WebDefinition> instead.
我想,这会告诉你所需要的一切。将其更改为WebDefinition?
(又名Nullable<WebDefinition>
确实可以解决问题。
但关键点是:阅读例外和InnerException
。
IMO,这里更好的“修复”是将其设为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; }
}
答案 1 :(得分:0)
如果您使用的是C#4.0,请尝试
public class MyDic
{
...
public List<WebDefinition?> WebDefinitions; //note the ? after your type.
...
}
哎呀我打算删除xelementnull部分。因此List本身可以为null,因此我假设您正在尝试允许WebDefinition为null。使用“?”将允许它成为可以为空的类型..它几乎正在做你的属性正在做的事情。
你也可以使用int来执行此操作.. decalre像public int一样的int? myInt = null;它会起作用。
http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx