【发布时间】:2014-02-19 10:44:12
【问题描述】:
这是给我未来的自己的便条,也是为了他人的利益。 所描述的行为并不明显......
我有一点 C#:
public enum Choices
{
One,
Two,
Three,
}
public class Element
{
List<Choices> _allowedChoices;
[XmlAttribute]
public List<Choices> AllowedChoices
{
get {return _allowedChoices ?? ( _allowedChoices = new List<Choices>() );}
set { _allowedChoices = value; }
}
}
[Test]
public void testing_empty_enum_list_serialization()
{
var ser = new XmlSerializer(typeof (Element));
using (var sw = new StringWriter())
{
ser.Serialize(sw, new Element
{
AllowedChoices = {},
});
var text = sw.ToString();
Console.WriteLine(text);
using (var sr = new StringReader(text))
{
var deserialized = (Element) ser.Deserialize(sr);
}
}
}
如果我使用 XmlSerializer 将其序列化为 xml,我会得到:
(注意末尾的空 AllowedChoices 属性)
<?xml version="1.0" encoding="utf-16"?>
<Element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" AllowedChoices="" />
如果我然后使用 XmlSerializer 反序列化这个 xml,我就像这样:
System.InvalidOperationException : There is an error in XML document (2, 109).
----> System.InvalidOperationException : Instance validation error: '' is not a valid value for Choices.
这是一个空的 list 枚举,可以无错误地序列化,Y U NO 反序列化!?
【问题讨论】:
标签: c# enums attributes xmlserializer