C#DataContractSerializer SerializationException,在对象字段中设置枚举 [英] C# DataContractSerializer SerializationException with Enum set in object field

查看:212
本文介绍了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);
}
}
}

公开枚举MyEnum
{
一,
二,


为什么在 _TestVariable 设置为枚举值?

 新的TestClass(1).Save(); // Works 
new TestClass(asdfqwer)。Save(); // Works
new TestClass(DateTime.UtcNow).Save(); // Works
new TestClass(MyEnum.One).Save(); //失败

抛出的异常是:

  System.Runtime.Serialization.SerializationException:键入'xxx.MyEnum',数据合约名称为xxx.MyEnum:http://schemas.datacontract.org/2004/07/Tests'不是预期的。考虑使用DataContractResolver或者将静态不知道的任何类型添加到已知类型的列表中 - 例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型的列表中。 


解决方案

你应该使用 KnownTypeAttribute

  [DataContract] 
[KnownTypeAttribute(typeof(MyEnum))]
public class TestClass


Given the following code,

[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
}

Why does it fail to serialize when _TestVariable is set to an Enum value?

new TestClass(1).Save(); // Works
new TestClass("asdfqwer").Save(); // Works
new TestClass(DateTime.UtcNow).Save(); // Works
new TestClass(MyEnum.One).Save(); // Fails

The exception thrown is:

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.

解决方案

You should use KnownTypeAttribute on TestClass.

[DataContract]
[KnownTypeAttribute(typeof(MyEnum))]
public class TestClass

这篇关于C#DataContractSerializer SerializationException,在对象字段中设置枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆