C#DataContractSerializer序列化异常,在对象字段中设置了枚举

mik*_*ike 1 c# enums exception datacontractserializer

鉴于以下代码,

[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
}
Run Code Online (Sandbox Code Playgroud)

_TestVariable设置为Enum值时,为什么无法序列化?

new TestClass(1).Save(); // Works
new TestClass("asdfqwer").Save(); // Works
new TestClass(DateTime.UtcNow).Save(); // Works
new TestClass(MyEnum.One).Save(); // Fails
Run Code Online (Sandbox Code Playgroud)

抛出的异常是:

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.
Run Code Online (Sandbox Code Playgroud)

arc*_*hil 5

您应该在TestClass上使用KnownTypeAttribute.

[DataContract]
[KnownTypeAttribute(typeof(MyEnum))]
public class TestClass
Run Code Online (Sandbox Code Playgroud)