2009-10-21 38 views
0

我有以下方法:如何訪問屬性在C#的.NET使用反射一個索引的每個memebr 2.0

object GetIndexer() 

該方法的結果是所述類型的分度器:

SomeCollection<T> 

現在T可以是任何東西,通過我知道,每個T擴展了Y型

我試圖鑄造

SomeCollection<Y> result= (SomeCollection<Y>) GetIndexer() 

它沒有工作。

我需要知道的是如何訪問索引器中的每個項目的屬性SomeCollection使用反射?

回答

2

對每個項目使用GetType(),然後調用GetProperties()GetProperty(propertyName)獲取PropertyInfo。有了這個,你可以打電話給GetValue()傳遞你的對象。

一個例子:

List<object> objects = new List<object>(); 
    // Fill the list 
    foreach (object obj in objects) 
    { 
     Type t = obj.GetType(); 
     PropertyInfo property = t.GetProperty("Foo"); 
     property.SetValue(obj, "FooFoo", null); 
     Console.WriteLine(property.GetValue(obj, null));    
    } 
+0

不幸的是索引器對象沒有實現IEnumerable接口,所以每個接口都沒有。 – 2009-10-21 20:37:41

0

一些背景將是有益的,但它聽起來像是你有類似

class Foo<T> where T : Y { 
    object GetIndexer() { /* ... */ } 
} 

在這種情況下,爲什麼不只是

SomeCollection<Y> GetIndexer() { /* */ } 

這樣,不需要強制轉換。

但是我對使用術語「索引器」有點困惑。對於C#索引器的重載[]運算符的類型的方式,這樣就可以做這樣的事情:

MyCollectionType c = new MyCollectionType() 
c["someValue"] 

他們像這樣定義:

class MyCollectionType { 
    public string this [string index] // This particular indexer maps strings to strings, but we could use other types if we wished. 
    get {} // Defines what to do when people do myCollection["foo"] 
    set {} // Defines what to do when people do myCollection["foo"] = "bar" 
} 

類型的對象SomeCollection<Y>不是索引器,它是一個集合。

0

SomeCollection<T> enumerable?如果是這樣你可以做

var transformed = new SomeCollection<Y>(); 

var someObjectCollection = (IEnumberable)GetIndexer(); 
foreach (var someObjectin someObjectCollection); 
    transformed.Add((Y)someObject); 

或等到C#4.0給我們更多的協方差和反變量選項。

+0

請注意,即使在C#4.0中,類也不能聲明爲協變。接口,但是,可以。 – Joren 2009-10-21 19:53:06

0

循環遍歷列表是枚舉過程。使用枚舉器最簡單。這是(在C#中):任何實現IEnumberable

如果您嘗試循環的對象是您自己製作的對象之一,我建議您實施IEnumberable。如果不是,你可以提供關於這個特定第三方對象的更多信息嗎?也許還有其他人也需要這樣使用它,也許他們的工作可以通過我們其中一個人在網上找到。

相關問題