C# 如何在xml序列化中显示数据类型?
我有这门课:C# 如何在xml序列化中显示数据类型?,c#,xml,xml-serialization,C#,Xml,Xml Serialization,我有这门课: public class Computer { [XmlAttribute("StorageType")] public int StorageType { get; set; } [XmlAttribute("StorageName")] public string StorageName { get; set; } public string IPAddress { get; set;
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”):
127.0.0.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>
127.0.0.1
计算机1
注意IPAddress元素上的DataType=“string”
<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>