2008-09-26 113 views

回答

9

还有Type.InvokeMember

public static class ReflectionExt 
{ 
    public static object GetAttr(this object obj, string name) 
    { 
     Type type = obj.GetType(); 
     BindingFlags flags = BindingFlags.Instance | 
           BindingFlags.Public | 
           BindingFlags.GetProperty; 

     return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null); 
    } 
} 

哪位能等中使用:

object value = ReflectionExt.GetAttr(obj, "PropertyName"); 

或(作为一个扩展法):

object value = obj.GetAttr("PropertyName"); 
3

为此使用反射。

Type.GetProperty()Type.GetProperties()每个返回PropertyInfo实例,它们可用于读取对象的属性值。

var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null) 

Type.GetMethod()Type.GetMethods()每个返回MethodInfo情况下,其可用于在对象上执行的方法。

var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null); 

如果你不一定知道的类型(这将是一点点奇怪,如果你新的属性名),比你可以做这样的事情为好。

var result = dt.GetType().GetProperty("Year").Invoke(dt, null); 
1

是的,你可以做到这一点...

typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null); 
0

有可以使用object.GetType创建的System.Reflection.PropertyInfo类()。GetProperties中()。这可以用来使用字符串探测对象的属性。 (类似的方法存在对象方法,字段等)

我不认为这会帮助你实现你的目标。你应该直接创建和操作对象。例如,控件具有可以设置的Name属性。