2010-12-23 59 views
0
class A 
{ 
    public string a { get; set; } 
    --and so on-- //lets we have 30-50 class variables// 
} 

我知道它的壞處。但我怎麼才能得到的所有變量的值只是循環和不知道他們的名字只是對象或類的實例?在不知道名字的情況下獲取對象的屬性值?

for(int i;i<30;i++) 
{ 
    variable[i] = object.? ; 
} 
+0

可以舉一些例子嗎? – user426306 2010-12-23 11:42:41

+0

好的我已經糾正了 – user426306 2010-12-23 11:48:07

回答

6

使用反射。

typeof(A).GetFields() 
typeof(A).GetProperties() 
+0

請記住,雖然這個反射是一個性能殺手...我嘗試了一個OR/M一次來做一些自動映射 – Ozzy 2010-12-23 11:36:27

0

在你的例子中,你有一個字段而不是屬性。下面顯示瞭如何迭代類型的所有成員的示例。您可以過濾下來使用FindMembers代替GetMemebrs

public class Reflector 
{ 
    public void ShowMembers(object o) 
    { 
     Type type = o.GetType(); 
     foreach (MemberInfo member in type.GetMembers()) 
     { 
      Console.WriteLine("{0} is a {1}", member.Name, member.MemberType); 
     } 
    } 
} 

運行上面的代碼對一個按鈕,你喜歡的東西:

...skip... 
ManipulationDelta is a Event 
ManipulationInertiaStarting is a Event 
ManipulationBoundaryFeedback is a Event 
ManipulationCompleted is a Event 
IsDefaultProperty is a Field 
IsCancelProperty is a Field 
IsDefaultedProperty is a Field 
... 

所以僅僅是明確的:

Public string a; 

是a字段,而

public string a { get; set; } 

將是一個財產。

我沒有真正回答這個問題。這對我來說很聰明。

public class Reflector 
{ 
    public void ShowMembers(object o) 
    { 
     Type type = o.GetType(); 
     foreach (MemberInfo member in type.GetMembers()) 
     { 
      Console.WriteLine("{0} is a {1}", member.Name, member.MemberType); 
     } 
    } 

    public void Set(object o, string fieldName, int val) 
    { 
     MemberInfo[] info = o.GetType().GetMember(fieldName); 
     FieldInfo field = info[0] as FieldInfo; 
     field.SetValue(o, val); 
    } 

    public int x; 
} 

如果我打電話reflector.Set(reflector, "x", 10);所以我打電話集本身,上述方法如果你想讀它的GetValue值的值設置爲10。

相關問題