如何定义对象属性的类型

发布于 2024-12-25 09:51:34 字数 828 浏览 5 评论 0 原文

当我获得具有不同属性类型的对象时,我需要定义每个对象属性的类型,并根据它 - 使用不同的方法序列化每个属性。我知道如何序列化具有不同类型的对象,但是我怎么能说这个属性应该与这个方法一起使用,而另一个属性应该与我不知道的另一个方法一起使用。

这是我的类的一个示例:

[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) {}

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

public static string XmlSerializeUsualTypes(Object item) {}

here I serialize Dictionary properties

public static string XmlSerializeDictionaryTypes(Object item) {}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

渡你暖光 2025-01-01 09:51:34

继承 Dictionary 并实现 XmlSerializeDictionaryTypes 方法的“nofollow">IXmlSerialized 接口。

public class MyXmlDictionary<K, V> : Dictionary<K,V>, IXmlSerializable
{
    // … implement IXmlSerializable methods here …
}

XmlSerializer 遇到实现 IXmlSerialized 的属性时(例如,当序列化 Person 对象时),它将调用 IXmlSerialized.WriteXml (在 poperty 的类型上实现,例如在我们的例子中为 MyXmlDictionary 序列化该属性。

Inherit Dictionary<K,V> and implement the IXmlSerializable interface using your XmlSerializeDictionaryTypes method.

public class MyXmlDictionary<K, V> : Dictionary<K,V>, IXmlSerializable
{
    // … implement IXmlSerializable methods here …
}

When the XmlSerializer encounters a property implementing IXmlSerializable (e.g. when serializing the Person object) it will call IXmlSerializable.WriteXml (implemented on the poperty's type, e.g. MyXmlDictionary<K,V> in our case) to serialize that property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文