反思帮助。根据类的属性从类中创建一个集合?

时间:2009-10-06 19:08:57

标签: c# reflection collections

我需要一些帮助。我很反思。我们正在使用第三方api,它返回一个名为“AddressList”的类。它的公共属性字面上称为Address1,Address1Name,Address1Desc,Address2,Address2Name,Address2Desc,Address3,Address3Name,Address3Desc,... Address99,Address99Name,Address99Desc ..还有一些其他属性。我有一个名为“SimpleAddress”的类,它只有3个属性(地址,名称,描述)。我想要做的是当我返回“AddressList”类时,我想通过AddressDesc99循环AddressDesc1 ...并且无论哪个都不为null或空,我想创建一个“SimpleAddress”的实例,填充它的属性,并将其添加到列表...有人能指出我正确的方向吗?显然,如果“AddressList”是某种集合,那会更好,但遗憾的是它不是。它是从大型机的返回字符串生成的。

感谢您的帮助, 〜在圣地亚哥

6 个答案:

答案 0 :(得分:6)

<挑。你可以这样做:

List<SimpleAddress> addresses = new List<SimpleAddress>();

string addressPropertyPattern = "Address{0}";
string namePropertyPattern = "Address{0}Name";
string descPropertyPattern = "Address{0}Desc";

for(int i = 1; i <= MAX_ADDRESS_NUMBER; i++)
{
    System.Reflection.PropertyInfo addressProperty = typeof(AddressList).GetProperty(string.Format(addressPropertyPattern, i));
    System.Reflection.PropertyInfo nameProperty = typeof(AddressList).GetProperty(string.Format(namePropertyPattern, i));
    System.Reflection.PropertyInfo descProperty = typeof(AddressList).GetProperty(string.Format(descPropertyPattern, i));

    SimpleAddress address = new SimpleAddress();

    address.Address = (string)addressProperty.GetValue(yourAddressListObject, null);
    address.Name = (string)nameProperty.GetValue(yourAddressListObject, null);
    address.Description = (string)descProperty.GetValue(yourAddressListObject, null);

    addresses.Add(address);
}

答案 1 :(得分:3)

首先获取相关类的类型并调用GetProperties方法。

PropertyInfo[] properties = myMainframeObject.GetType().GetProperties();

每个PropertyInfo都有一个可用于匹配的Name属性(字符串)。遍历所有属性,并编写创建SimpleAddress新实例的代码。

在此循环中,您可以访问大型机对象并提取所需的属性值:

// imagine that in this case, 'p' is a PropertyInfo that represents Address2Name
var simpleAddress = new SimpleAddress();
simpleAddress.Name = p.GetValue(myMainframeObject, null);

(null永远不会用于普通属性 - 它适用于索引属性。)

答案 2 :(得分:2)

您应该可以执行以下操作:

List<SimpleAddress> CreateList(AddressList address)
{
    List<SimpleAddress> values = new List<SimpleAddress>();
    Type type = address.GetType();
    for (int i=1;i<=99;++i)
    {
         string address = type.GetProperty("Address" + i.ToString()).GetValue(address,null).ToString();
         string addressDesc = type.GetProperty("Address" + i.ToString() + "Desc").GetValue(address,null).ToString();
         string addressName = type.GetProperty("Address" + i.ToString() + "Name").GetValue(address,null).ToString();


         if (!string.IsNullOrEmpty(addressDesc) || !string.IsNullOrEmpty(addressName) || !string.IsNullOrEmpty(address)  )
              value.Add(new SimpleAddress(address,addressDesc,addressName));
    }

    return values;
 }

答案 3 :(得分:1)

未经测试(出于显而易见的原因),但类似于:

List<SimpleAddress> newList = new List<SimpleAddress>();
AddressList list = ...
Type type = list.GetType();
PropertyInfo prop1, prop2, prop3;
int index = 1;
while((prop1 = type.GetProperty("Address" + index)) != null
   && (prop2 = type.GetProperty("Address" + index + "Name")) != null
   && (prop3 = type.GetProperty("Address" + index + "Desc")) != null) {
    string addr = (string) prop1.GetValue(list, null),
           name = (string) prop2.GetValue(list, null),
           desc = (string) prop3.GetValue(list, null);

    if(addr == null || name == null || desc == null) {
       continue; // skip but continue
    }

    SimpleAddress newAddr = new SimpleAddress(addr, name, desc);
    newList.Add(newAddr);
    index++;
}

答案 4 :(得分:1)

如果你想使用linq

public static class MyTools
{
    public static TReturn GetValue<TReturn>(this object input, 
                                            string propertyName)
    {
        if (input == null)
            return default(TReturn);
        var pi = input.GetType().GetProperty(propertyName);
        if (pi == null)
            return default(TReturn);
        var val = pi.GetValue(input, null);
        return (TReturn)(val == null ? default(TReturn) : val);
    }

    public static string GetString(this object input, string propertyName)
    {
        return input.GetValue<string>(propertyName);
    }

    public static List<SimpleAddress> GetAddress(this MyObject input)
    {
        return (
            from i in Enumerable.Range(1, 2)
            let address = input.GetString("Address" + i.ToString())
            let name = input.GetString("Address" + i.ToString() + "Name")
            let desc = input.GetString("Address" + i.ToString() + "Desc")
            select new SimpleAddress() { Address = address, 
                                         Name = name, 
                                         Description = desc }
           ).ToList();
    }
}

答案 5 :(得分:0)

var addrList = new AddressList
{
    Address1Name = "ABC",
    Address1Desc = "DEF",
    Address1 = "GHI",
    Address3Name = "X",
    Address3Desc = "Y",
    Address3 = "Z"
};

var addresses =
        from i in Enumerable.Range(1, 99)
        let desc = typeof(AddressList).GetProperty(string.Format("Address{0}Desc", i)).GetValue(addrList, null) as string
        let name = typeof(AddressList).GetProperty(string.Format("Address{0}Name", i)).GetValue(addrList, null) as string
        let address = typeof(AddressList).GetProperty(string.Format("Address{0}", i)).GetValue(addrList, null) as string
        where !string.IsNullOrEmpty(address)
        select new SimpleAddress
        {
            Name = name,
            Description = desc,
            Address = address
        };