【问题标题】:How can I properly store an enum value with XmlSerializer (.NET) when the enum value is stored as object当枚举值存储为对象时,如何使用 XmlSerializer (.NET) 正确存储枚举值
【发布时间】:2019-05-09 11:05:00
【问题描述】:

我想保存一个包含基本上可以是任何类型的值的对象。我正在使用 XmlSerializer 来执行此操作,它可以正常工作,但有一个例外:如果值是枚举,则序列化程序将值存储为整数。如果我将其加载回来并使用该值从字典中读取,我会得到 KeyNotFoundException。

是否有任何优雅的方法可以将枚举保存为枚举或避免 KeyNotFoundException 并仍然使用 XmlSerializer? (这里回滚不是一个好的选择,容器和字典必须支持所有类型)

这里有一段简化的代码来演示这个问题:

public enum SomeEnum
{
    SomeValue,
    AnotherValue
}

// Adding [XmlInclude(typeof(SomeEnum))] is no proper solution as Key can be any type
public class GenericContainer
{
    public object Key { get; set; }
}

private Dictionary<object, object> SomeDictionary = new Dictionary<object, object>();

public void DoSomething()
{
    SomeDictionary[SomeEnum.AnotherValue] = 123;

    var value = SomeDictionary[SomeEnum.AnotherValue];

    Save(new GenericContainer { Key = SomeEnum.AnotherValue}, "someFile.xml");
    var genericContainer = (GenericContainer)Load("someFile.xml", typeof(GenericContainer));

    // Throws KeyNotFoundException
    value = SomeDictionary[genericContainer.Key];
}

public void Save(object data, string filePath)
{
    var serializer = new XmlSerializer(data.GetType());
    using (var stream = File.Create(filePath))
    {
        serializer.Serialize(stream, data);
    }
}
public object Load(string filePath, Type type)
{
    var serializer = new XmlSerializer(type);
    using (var stream = File.OpenRead(filePath))
    {
        return serializer.Deserialize(stream);
    }
}

【问题讨论】:

标签: c# .net xml enums xmlserializer


【解决方案1】:

你可以把属性放到你的枚举中

public enum Simple
{
      [XmlEnum(Name="First")]
      one,
      [XmlEnum(Name="Second")]
      two,
      [XmlEnum(Name="Third")]
      three,
}

原文: How do you use XMLSerialize for Enum typed properties in c#?

【讨论】:

  • 这不能解决我的问题,因为它只会更改 XML 文件中枚举值的字符串。但是为此枚举值必须直接保存,而不是作为对象。它仍然保存为整数。
猜你喜欢
  • 2016-11-10
  • 2013-03-02
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
  • 2014-11-13
相关资源
最近更新 更多