0

我需要将内部类型转换为通用名称/值对列表。这样我们就可以以通用/标准的方式发送大量信息,而不必担心添加新字段时会更改架构等。我的问题是如何填充通用结构。

例如一组内部字段:

[Serializable]
public class Location
{
    public string sAddress { get; set; }
    public string sCity { get; set; }
    public int iZipCode { get; set; }
}

需要转化为:

<AttributeList>
  <Attribute>
    <Name>sAddress</Name>
    <Value>123 ABC Street</Value>
    <DataType>string</DataType>
  </Attribute>
</AttributeList>

重复 sCity 和 iZipCode。

只是我不确定执行此操作的最佳方法,因为某些字段(例如 iZipCode)可能未实例化。

我能想到的唯一方法是让代码在内部数据结构中查找每个特定字段,确保它不为空,然后从包含实际内部字段名称的枚举对象(或其他东西)映射 Attribute.Name (如 sAddress),然后是值,然后设置类型,因为我知道我正在寻找的字段是什么类型。

如果只有 3 个字段就可以了,但是会远不止这些,而且这似乎是一个不好的方法,好像添加了一个新字段我需要更新代码 - 更不用说很多代码基本上做同样的事情。

理想情况下,我想要一些可以通用地循环遍历内部结构中的所有内容的东西,例如位置,并自动检查字段是否存在,如果没有每个字段的特定代码,则提取字段名称、值和类型。

我不知道这是否可能,任何建议将不胜感激!

4

2 回答 2

1

你可以通过反射来做到这一点。这是一个例子:

PropertyInfo[] properties
properties = typeof(Location).GetProperties(BindingFlags.Public);
StringBuilder sb = new StringBuilder()
foreach (PropertyInfo p in properties)
{
    sb.Append(p.Name)
    sb.Append(p.PropertyType)
    sb.Append(p.GetValue(null,null))
}

显然更改格式以使其适合您。

您需要使用 System.Reflection 命名空间。

编辑:我刚刚看到您的编辑,并且您希望输出为 XML。XML 序列化可能也值得一看。

于 2013-01-30T16:26:07.350 回答
1

这会将您的示例吐出到 XML 中。如果要支持索引属性,则需要做一些额外的工作:

Location loc = new Location { sAddress = "123 ABC Street",
                              sCity = "Fake City",
                              iZipCode = 12345 };

XDocument doc = new XDocument();
XElement attrList = new XElement("AttributeList");
doc.Add(attrList);

foreach (PropertyInfo propInfo in loc.GetType().GetProperties())
{
    XElement attrRoot = new XElement("Attribute", new XElement("Name") { Value = propInfo.Name });
    object propValue = propInfo.GetValue(loc, null);
    attrRoot.Add(new XElement("Value") { Value = propValue == null ? "null" : propValue.ToString() });
    attrRoot.Add(new XElement("DataType") { Value = propInfo.PropertyType.ToString() });
    attrList.Add(attrRoot);
}
于 2013-01-30T16:36:35.537 回答