【发布时间】:2012-03-02 20:08:56
【问题描述】:
我为此使用 .NET 3.5。
我有一个枚举:
[System.SerializableAttribute()]
public enum MyEnum
{
[System.Xml.Serialization.XmlEnumAttribute("035")]
Item1,
Item2
}
我在一个类中使用这个枚举:
[System.SerializableAttribute()]
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public MyEnum MyEnum { get; set; }
}
现在我想创建一个新的 Eplomyee 实例,通过从字符串转换来设置 MyEnum 属性。 然后将其序列化并保存在一个文件中。
Employee bob = new Employee() {Id = 1, Name = "Bob"};
bob.MyEnum = (MijnEnum)Enum.Parse(typeof(MyEnum), string.Format(CultureInfo.InvariantCulture, "{0}", "035"));
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
FileInfo fi = new FileInfo(@"C:\myfile.xml");
using (FileStream stream = fi.OpenWrite())
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, OmitXmlDeclaration = true, Indent = true };
using (XmlWriter writer = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(writer, bob); // this is place where it goes wrong
}
}
如果我对此进行调试,我会看到 bob.MyEnum 的值是 35
当我尝试序列化时,我得到一个异常:
生成 XML 文档时出错。
实例验证错误:“35”不是 WindowsFormsApplication.MyEnum。
出了什么问题,我该如何解决?
【问题讨论】:
-
你做错了。特别是
Enum.Parse。 -
您是否尝试在枚举声明中指定:
Item1 = 25,? -
你知道你可以只使用 [Serializable] 而不是 [System.SerializableAttribute()]?
-
@leppie:启发我。也许这可以解决我的问题。
-
@Botz3000:是的,我知道。该属性是自动生成的,因此是全名...
标签: c# enums xml-serialization