如何定义对象属性的类型
当我获得具有不同属性类型的对象时,我需要定义每个对象属性的类型,并根据它 - 使用不同的方法序列化每个属性。我知道如何序列化具有不同类型的对象,但是我怎么能说这个属性应该与这个方法一起使用,而另一个属性应该与我不知道的另一个方法一起使用。
这是我的类的一个示例:
[XmlType("Person")] // define Type
public class Person
{
[XmlElement("PropertyType")]
public PropertyType PropertyType { get; set; }
[XmlElement("ID")]
public string ID { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("City")]
public string City { get; set; }
[XmlElement("Age")]
public Dictionary<object, object> Age { get; set; }
}
这里我序列化 int、string、List 属性
public static string XmlSerializeUsualTypes(Object item) {}
这里我序列化 Dictionary 属性
public static string XmlSerializeDictionaryTypes(Object item) {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
继承
Dictionary
并实现 XmlSerializeDictionaryTypes 方法的“nofollow">IXmlSerialized
接口。当
XmlSerializer
遇到实现IXmlSerialized
的属性时(例如,当序列化Person
对象时),它将调用IXmlSerialized.WriteXml
(在 poperty 的类型上实现,例如在我们的例子中为MyXmlDictionary
) 序列化该属性。Inherit
Dictionary<K,V>
and implement theIXmlSerializable
interface using yourXmlSerializeDictionaryTypes
method.When the
XmlSerializer
encounters a property implementingIXmlSerializable
(e.g. when serializing thePerson
object) it will callIXmlSerializable.WriteXml
(implemented on the poperty's type, e.g.MyXmlDictionary<K,V>
in our case) to serialize that property.