2011-04-21 214 views
0

是否可以在C#中動態訪問對象屬性?我似乎無法想出一個辦法。 VS似乎每次都在吼我。動態訪問對象屬性

這裏是一個例子來說明我想要做什麼。

因此,我們有兩個對象,我們稱之爲汽車。

Car CAR1 = new Car(); 
Car CAR2 = new Car(); 

現在說我有一個名爲myArray的數組中的CAR1和CAR2;

int count = myArray.length. 

所以這裏是問題,我想能夠循環,雖然數組能夠訪問對象屬性的。

E.g

for (int i =0; i < count; i++) 
{ 

    myArry[i].GetProperty; 
    myArry[i].GetProperty2; 
    myArry[i].GetProperty3; 

} 

Howerver,上面,VS沒有。無論如何,我可以做到這一點?

+2

你得到的錯誤是什麼? – locoboy 2011-04-21 17:29:00

+1

或者至少發佈你的數組聲明*和你得到的錯誤*。 – 2011-04-21 17:33:37

回答

1

如果需要,可以使用通用的List<T>而不是數組。

public class Car{ 
    public string Color {get;set;} 
    public int NumberOfDoors {get;set;} 
} 
public static void Main() { 
    var carList = new List<Car>(); 
    carList.Add(new Car() { Color = "Red", NumberOfDoors = 2 }); 
    carList.Add(new Car() { Color = "Blue", NumberOfDoors = 4}); 

    for (int i = 0; i < carList.Count; i++){ 
     Console.WriteLine(carList[i].Color); 
     Console.WriteLine(carList[i].NumberOfDoors); 
    } 
} 
+0

雖然一個體面的建議本身,這似乎沒有任何關係的問題。 – 2011-04-21 17:33:04

+0

@Adam:你如何閱讀這個問題? – 2011-04-21 17:35:00

+1

他在訪問數組成員上的屬性時似乎收到錯誤。它看起來更像是一個簡單的(但未定義的)語法錯誤。 C#中的 – 2011-04-21 17:48:36

1

難道你錯過了myArray的「a」嗎?

0

如果沒有實際的代碼或錯誤,您可能無法確定,但可能無法訪問屬性而無需執行任何操作。 Console.WriteLine(myArray[i].GetProperty);是否工作?

+0

沒有,這不起作用。 – Andy12 2011-04-21 18:38:02

+0

@Andy,你能告訴我們使用你得到的實際錯誤,並告訴我們你的所有代碼嗎?沒有這個,我們只是盲目猜測。 – svick 2011-04-21 18:57:14

1

看起來很明顯,你在這裏需要的是使用反射嗎?如果沒有,我闖到大明白這個問題在所有...

在的情況下,...

獲取屬性,使用

var t = typeof(Car);//get the type "Car" 
    var carProperties = t.GetProperties();//get all the public instance properties of the Car type 
    var property01 = t.GetProperty("MyPropertyOne");//get a PropertyInfo for the public instance property "MyPropertyOne" of the type "Car" 

然後,如果你想dynmacaly獲得每個汽車對象的值:

for (int i =0; i < count; i++) 
{   
    var property01 = t.GetProperty("MyPropertyOne"); 
    var propertyOneValue = property01.GetValue(myArry[i],null); 
    Console.WriteLine(propertyOneValue); 

    var property02 = t.GetProperty("MyPropertyTwo"); 
    var propertyTwoValue = property02 .GetValue(myArry[i],null); 
    Console.WriteLine(propertyTwoValue); 

    //And so on... 
} 

如果任何機會,這是你在找什麼,要知道,使用反射(在leastin這種粗魯的方式)是drasticaly比訪問Ø慢對象屬性directy

+0

在C#中沒有變量類型,名爲var – Andy12 2011-04-21 18:37:36

+0

@andy很搞笑;-) – Bruno 2011-04-21 18:55:16

0

您可以使用GetProperties方法,這將允許您獲取該對象使用的所有屬性。 當需要在運行時訪問類屬性時,使用PropertyInfo類。PropertyInfo的實例將表示當前由該類訪問的當前屬性。 GetProperty方法返回一個PropertyInfo對象,而GetProperties返回一個PropertyInfo對象數組。 例如PropertyInfo [] PrObj = typeobj.Getproperties();