c# - 枚举的序列化失败

标签 c# enums xml-serialization

我为此使用 .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/

相关文章:

java - 如何从字节中获取枚举

wcf - 无法为 DataContract 中的字符串类型获取 minOccurs ="1"maxOccurs ="1"

c# - XML 到 C# 类

c# - 返回 NULL 的 Trello.NET 对象

c# - DataGrid 不能输入逗号或点作为值?

C#/.Net - 解析 XML/XML 的快速方法 -> Json

c# - .Net Core 2.1 似乎忽略了 modelBuilder.Entity<TEntity>().HasData

java - 为什么 EnumMap 构造函数需要类参数?

c# - 从资源写入文件,其中资源可以是文本或图像

c# - 是否可以向序列化集合添加属性?