C# DataContractSerializer SerializationException with Enum set in object field

試著忘記壹切 提交于 2019-12-06 15:44:58

You should use KnownTypeAttribute on TestClass.

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

Another option that you could employ to avoid having to put the KnownType attribute all over the place is to use type deduction to do the work for you.

class Program
{
    static void Main(string[] args)
    {
        TestClass.Create(1).Save(); // Works
        TestClass.Create("asdfqwer").Save(); // Works
        TestClass.Create(DateTime.UtcNow).Save(); // Works
        TestClass.Create(MyEnum.One).Save(); // Fails
    }
}

public class TestClass
{
    public static TestClass<T> Create<T>(T value)
    {
        return new TestClass<T>(value);
    }
}

[DataContract]
public class TestClass<T>
{
    [DataMember]
    public T _TestVariable;

    public TestClass(T value)
    {
        _TestVariable = value;
    }

    public void Save()
    {
        using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(new MemoryStream()))
        {
            DataContractSerializer ser = new DataContractSerializer(typeof(TestClass<T>));
            ser.WriteObject(writer, this);
        }
    }
}

public enum MyEnum
{
    One,
    Two,
    Three
}

MyEnum is not marked as serializable. Adding DataContractAttribute to MyEnum should fix it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!