[英]How to define a type of object property
When I get an object with different property types I need to define a type of each object property and depending on it - serialize each property with different method. 当我得到一个具有不同属性类型的对象时,我需要定义每个对象属性的类型并根据它-用不同的方法序列化每个属性。 I know how to serialize object with different type, but how can I said that this property should be used with this method and another with another method I don't know.
我知道如何序列化具有不同类型的对象,但是如何说此属性应与此方法一起使用,而另一个应与另一个我不知道的方法一起使用。
Here is an example of my class: 这是我班的一个例子:
[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; }
}
here I serialize int,string, List properties 在这里我序列化int,string,List属性
public static string XmlSerializeUsualTypes(Object item) {}
here I serialize Dictionary properties 在这里我序列化字典属性
public static string XmlSerializeDictionaryTypes(Object item) {}
Inherit Dictionary<K,V>
and implement the IXmlSerializable
interface using your XmlSerializeDictionaryTypes
method. 继承
Dictionary<K,V>
并使用XmlSerializeDictionaryTypes
方法实现IXmlSerializable
接口。
public class MyXmlDictionary<K, V> : Dictionary<K,V>, IXmlSerializable
{
// … implement IXmlSerializable methods here …
}
When the XmlSerializer
encounters a property implementing IXmlSerializable
(eg when serializing the Person
object) it will call IXmlSerializable.WriteXml
(implemented on the poperty's type, eg MyXmlDictionary<K,V>
in our case) to serialize that property. 当
XmlSerializer
遇到一个实现IXmlSerializable
的属性(例如,序列化Person
对象时)时 ,它将调用IXmlSerializable.WriteXml
(在MyXmlDictionary<K,V>
的类型上实现,例如MyXmlDictionary<K,V>
)以对该属性进行序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.