如何使用XmlSerializer的序列化Object类型的属性 [英] How to serialize property of type Object with XmlSerializer
本文介绍了如何使用XmlSerializer的序列化Object类型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个属性:
public object Tag
但它可以包含有限数量的类型,可惜没有基本类型(除对象类型)。但是,当我序列化这个属性的对象,它不会序列化。有没有一种方法来指示XmlSerializer的可能的类型?
but it can contain finite number of types, unfortunately without base type (except object type). But when I serialize the object with this property, it doesn't get serialized. Is there a way to instruct XmlSerializer with possible types?
推荐答案
我不建议这样做,但是,是的,你可以使用 [的XmlElement]
等来告诉它为成员有关多个候选类型:
I don't recommend this, but yes, you can use [XmlElement]
etc to tell it about multiple candidate types for a member:
public class Test
{
private static void Main()
{
var ser = new XmlSerializer(typeof (Test));
var obj = new Test {Value = "abc"};
ser.Serialize(Console.Out, obj);
obj = new Test { Value = 123 };
ser.Serialize(Console.Out, obj);
obj = new Test { Value = 456.7F };
ser.Serialize(Console.Out, obj);
}
[XmlElement("a", Type = typeof(int))]
[XmlElement("b", Type = typeof(string))]
[XmlElement("c", Type = typeof(float))]
public object Value { get; set; }
}
输出的重要位(忽略所有的xmlns
/ < XML>
等?)是:
The important bits of the output (ignoring all the xmlns
/ <?xml>
etc) are:
<Test>
<b>abc</b>
</Test>
<Test>
<a>123</a>
</Test>
<Test>
<c>456.7</c>
</Test>
这篇关于如何使用XmlSerializer的序列化Object类型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文