我为此使用 .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
当我尝试序列化时,出现异常:
There was an error generating the XML document.
Instance validation error: '35' is not a valid value for WindowsFormsApplication.MyEnum.
出了什么问题,如何解决?
最佳答案
让我们开始吧:
[System.SerializableAttribute()] // useless, valuetype is implicitly so
public enum MyEnum
{
[System.Xml.Serialization.XmlEnumAttribute("035")]
Item1,
Item2
}
现在,XmlEnumAttribute
控制该值在 XML 中的序列化和反序列化方式。
它与您的其余代码无关!(抱歉,大写,但似乎没有其他人明白这一点)。
因此,当 MyEnum.Item1
的值被序列化时,将发出“035”。
现在的问题是你想如何分配它。
很简单。就像平常一样分配即可。这些属性不会改变正常代码的语义,一切都保持不变。
示例:
Employee bob = new Employee() {Id = 1, Name = "Bob", MyEnum = MyEnum.Item1};
这里绝对没有理由考虑Enum.Parse
。枚举类型和值是静态已知的。
如果您确实想使用Enum.Parse
,请像平常一样使用它,例如:
Enum.Parse(typeof(MyEnum), "Item1")
关于c# - 枚举的序列化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9226378/