考慮下面的代碼設置,C#的DataContractSerializer SerializationException與枚舉對象場
[DataContract]
public class TestClass
{
[DataMember]
public object _TestVariable;
public TestClass(object value)
{
_TestVariable = value;
}
public void Save()
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(new FileStream("test.tmp", FileMode.Create)))
{
DataContractSerializer ser = new DataContractSerializer(typeof(TestClass));
ser.WriteObject(writer, this);
}
}
}
public enum MyEnum
{
One,
Two,
Three
}
爲什麼會失敗時_TestVariable
設置爲枚舉值序列化?
new TestClass(1).Save(); // Works
new TestClass("asdfqwer").Save(); // Works
new TestClass(DateTime.UtcNow).Save(); // Works
new TestClass(MyEnum.One).Save(); // Fails
引發的異常是:
System.Runtime.Serialization.SerializationException : Type 'xxx.MyEnum' with data contract name 'xxx.MyEnum:http://schemas.datacontract.org/2004/07/Tests' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
你試圖通過使用_TestVariable對象類型來解決什麼問題,也許你可以解釋真正的問題。 – 2011-04-07 07:23:48
請參閱類似問題的答案http://stackoverflow.com/a/8795410/52277 – 2013-05-29 18:11:54