2008-09-26 109 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屬性。