gpt4 book ai didi

在对象字段中设置枚举的 C# DataContractSerializer SerializationException

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:21 25 4
gpt4 key购买 nike

给定以下代码,

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

最佳答案

你应该使用 KnownTypeAttribute在测试类上。

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

关于在对象字段中设置枚举的 C# DataContractSerializer SerializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5577370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com