2012-07-06 16 views
3

我可能在這裏缺少基本知識,但我會去找它並提出問題。如何在C中動態獲取類元素

比方說,我們有一個字符串數組:

​​

,我們有一個類:

public class InventoryItem 
    { 
     public string ItemCode { get; set; } 
     public string ItemDescription { get; set; } 
    } 

我希望能夠引用動態基於價值觀的InventoryItem的屬性的陣列。

我需要遍歷數組並通過數組的當前字符串成員來獲取類的屬性值。

我該怎麼辦?

+0

如何ItemCode和ItemDescription申報? InventoryItem還在哪裏,請顯示代碼。 – 2012-07-06 10:16:17

+0

一種選擇是使用反射。見[這裏] [1]。 [1]:http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – Maarten 2012-07-06 10:17:08

回答

9

您使用反射:

foreach (var name in propertyNames) 
{ 
    // Or instance.GetType() 
    var property = typeof(InventoryItem).GetProperty(name); 
    Console.WriteLine("{0}: {1}", name, property.GetValue(instance, null)); 
} 

參見:

1

喬恩斯基特的答案是絕對正確的(他有沒有其他類型的?),並且如果需要動態訪問1000個InventoryItem對象,則工作得很好。但是如果你需要動態訪問更多的對象,比如說1000萬,反射開始變得非常緩慢。我有一個我曾經做過的小助手類,通過創建和編譯動態方法來訪問屬性,可以輕鬆訪問比反射速度快26倍的屬性(至少在我的計算機上)。它遠不及靜態訪問它的速度快,但是因爲您需要動態訪問它,所以這甚至不是一個考慮因素。這裏是你如何使用它:

var accessor = new DynamicPropertyAccessor(typeof(InventoryItem).GetProperty("ItemCode")); 

foreach (var inventoryItem in warehouse13) 
{ 
    Console.WriteLine("{0}: {1}", accessor.Name, accessor[inventoryItem]); 
} 

你也可以用它來設置一個值和:accessor[item] = "newValue"。如果您需要動態訪問多個屬性,則可以擁有一組訪問器。當您爲每個屬性創建一個DynamicPropertyAccessor並重用以訪問許多對象(或多次使用相同的對象)時,性能增益將會很大。

我已經張貼了DynamicPropertyAccessor類在這裏:https://gist.github.com/3059427