2014-02-14 32 views
2

我有一個具有多個ObservableCollections的類用於不同類型。現在,我想通過反射爲給定類型找到正確的Collection,因爲我不想構建一個if-monster,每次添加另一個Collection時都必須更新它。通過反射爲給定/動態類型查找ObservableCollection

本方法的第一步:

public ObservableCollection<T> GetObservableCollectionForType<T>() 
{ 

    foreach (PropertyInfo info in this.GetType().GetProperties()) 
    { 

     if (info.GetGetMethod() != null && info.PropertyType == typeof(ObservableCollection<T>)) 
     return (ObservableCollection<T>)this.GetType().GetProperty(info.Name).GetValue(this, null);     

    } 

    return null; 

} 

現在,我需要的第二種方法,它接受一個具體的對象作爲參數,並找到正確的集合。不知怎的,像這樣:

public ObservableCollection<T> GetObservableCollectionFor(object sObject) 
{ 

    Type wantedType = sObject.GetType(); 

    foreach (PropertyInfo info in this.GetType().GetProperties()) 
    { 

    if (info.GetGetMethod() != null && info.PropertyType == ObservableCollection<wantedType>) 
     return this.GetType().GetProperty(info.Name).GetValue(this, null); 

    } 

    return null; 

} 

任何想法如何實現這一點?

更新

A工作液:

public object GetObservableCollectionFor(object sObject) 
{ 

    Type wantedType = sObject.GetType(); 

    foreach (PropertyInfo info in this.GetType().GetProperties()) 
    { 

     if (info.GetGetMethod() != null && info.PropertyType == typeof(ObservableCollection<>).MakeGenericType(new[]{wantedType})) 
     return this.GetType().GetProperty(info.Name).GetValue(this, null); 

    } 

    return null; 

} 

這將返回正確的集合作爲對象。我仍然不知道如何投射到正確的通用類型,但投射到IList就足以添加和刪除。

+0

你不能只是根據我更新的答案添加一個明確的強制轉換,並將返回類型保留爲ObservableCollection ? – twrowsell

+0

看起來像編譯器不接受'ObservableCollection '作爲返回類型,只要方法調用沒有提供

回答

2

比較屬性的類型時,看起來您需要在ObservableCollection類型上添加對MakeGenericType()的調用。沒有測試過這一點,但也許像...

public ObservableCollection<T> GetObservableCollectionFor(object sObject) 
{ 

    Type wantedType = sObject.GetType(); 

    foreach (PropertyInfo info in this.GetType().GetProperties()) 
    { 

    if (info.GetGetMethod() != null && info.PropertyType == typeof(ObservableCollection<>).MakeGenericType(new[]{Type.GetType(wantedType)}) 

     return (ObservableCollection<T>)this.GetType().GetProperty(info.Name).GetValue(this, null); 

    } 

    return null; 

} 

編輯 爲了避免與值類型的開銷拳擊,上述方法定義可以通過從對象改變參數類型爲類型T

得到改善
public ObservableCollection<T> GetObservableCollectionFor(T sObject) 
+0

感謝,但似乎編譯器不接受無T參數的typeof(ObservableCollection)的使用 –

+0

@MartinTausch,我做了一個編輯。我忘了爲通用類型添加斜角括號。 – twrowsell

+0

啊,好吧。現在我可以編譯。但是他仍然不接受T在宣告退貨價值。我可以返回作爲對象,但不知道如何施展正確的然後... –