【发布时间】: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);
}
}
【问题讨论】:
-
您需要将
[XmlInclude(typeof(SomeEnum))]应用到您的班级。请参阅 Serializing a class with a generic Enum that can be different Enum types 和 Using XmlSerializer to serialize derived classes。事实上,这可能是重复的,同意吗? -
@dbc 为所有可能的枚举类型添加 XmlInclude 不是解决方案,因为密钥可以是任何类型,我不知道“用户”将使用什么类型。
-
我现在找到了解决办法,很简单:
标签: c# .net xml enums xmlserializer