string to variable name

前端 未结 4 504
一向
一向 2020-11-27 05:50

I have class(Customer) which holds more than 200 string variables as property. I\'m using method with parameter of key and value. I trying to supply key and value from xml f

4条回答
  •  迷失自我
    2020-11-27 06:20

    Well, you can use Type.GetProperty(name) to get a PropertyInfo, then call GetValue.

    For example:

    // There may already be a field for this somewhere in the framework...
    private static readonly object[] EmptyArray = new object[0];
    
    ...
    
    PropertyInfo prop = typeof(Customer).GetProperty(item.key);
    if (prop == null)
    {
        // Eek! Throw an exception or whatever...
        // You might also want to check the property type
        // and that it's readable
    }
    string value = (string) prop.GetValue(customer, EmptyArray);
    template.SetTemplateAttribute(item.key, value);
    

    Note that if you do this a lot you may want to convert the properties into Func delegate instances - that will be much faster, but more complicated. See my blog post about creating delegates via reflection for more information.

提交回复
热议问题