0

我有这个类:

public class Computer 
    {
        [XmlAttribute("StorageType")]
        public int StorageType { get; set; }

        [XmlAttribute("StorageName")]
        public string StorageName { get; set; }

        public string IPAddress { get; set; }
        public string Name { get; set; }
    }

我需要 xml 来显示某些元素中的数据类型(dt:dt="string"):

<fpc4:Computer StorageName="{D37291CA-D1A7-4F34-87E4-8D84F1397BEA}" StorageType="1">
        <fpc4:IPAddress dt:dt="string">127.0.0.1</fpc4:IPAddress>
        <fpc4:Name dt:dt="string">Computer1</fpc4:Name>
    </fpc4:Computer>

有什么建议么?

4

1 回答 1

1

您可以在您的类中创建一个属性,该属性充当子元素以充当数据类型属性,并使用给定对象上的反射执行以下操作。MethodBase 有一个名为 ReturnType 的属性,它将为您提供返回类型。

[XmlAttribute("DataType")]
public string DataType 
{
    get 
    { 
        return typeof(IPAddress).GetProperty("DataType").GetGetMethod().ReturnType.ToString();
    }
}

这将产生以下 xml 行

<fpc4:Computer StorageName="{D37291CA-D1A7-4F34-87E4-8D84F1397BEA}" StorageType="1">
        <fpc4:IPAddress DataType="string">127.0.0.1</fpc4:IPAddress>
        <fpc4:Name dt:dt="string">Computer1</fpc4:Name>
</fpc4:Computer>

注意 IPAddress 元素上的 DataType="string"。

于 2013-02-14T15:24:43.437 回答