我想保存一个对象,该对象包含的值基本上可以是任何类型。我正在使用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);
}
}
答案 0 :(得分:0)
您可以将属性放入枚举
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#?