[英]C# XmlSerializer can't serialize after casting member to System.Object
A simple struct: 一个简单的结构:
public struct TestA
{
public object value;
}
Create it and serialize it: 创建并序列化它:
List<string> value = new List<string>();
value.Add("a1");
TestA a = new TestA();
a.value = value;
MemoryStream stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(a.GetType());
xml.Serialize(stream, a);
Can't be serialized, InvalidOperationException: The type of the argument object 'System.Collections.Generic.List' is not primitive. 无法序列化,InvalidOperationException:参数对象'System.Collections.Generic.List'的类型不是原始类型。
If I change "public object value;"
如果更改
"public object value;"
to "public List<string> value;"
改为
"public List<string> value;"
, it can be serialized. ,可以序列化。
I want to use this object value
to store value with different types, so I make the type as object
. 我想使用该
object value
来存储具有不同类型的值,因此我将类型设置为object
。 Such as: 如:
a.value = new List<int>();
a.value = 3;
a.value = "a string";
This ought to do the job. 这应该做的工作。
[Serializable]
public class TestA : IXmlSerializable
{
public object value;
public XmlSchema GetSchema()
{
return (null);
}
public void ReadXml(XmlReader reader)
{
value = reader.ReadContentAsObject();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteValue(value);
}
}
Thanks both code4life and Soham, I haven't tested your idea, because I found a very simple way. 感谢code4life和Soham,我没有测试您的想法,因为我找到了一种非常简单的方法。 Give XmlSerializer the second paramter, give it the exact type of the
object value
. 给XmlSerializer第二个参数,给它确切的
object value
类型。
XmlSerializer xml = new XmlSerializer(a.GetType(), new Type[] { typeof(List<string>) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.