2015-08-20 55 views
0

它作爲具體的MyCollection的 和呼叫方法我有一個自定義集合類型 ObservableStateCollection,對於簡單的目的,是這樣的: 鑄鉛字通過反射

public class ObservableStateCollection<T> : IList<T>, INotifyCollectionChanged, INotifyPropertyChanged where T : StateObservable 
{ 
    private List<T> _items; 
    private List<T> _deleted; 

    public IEnumerator<T> GetEnumerator() 
    { 
     return _items.GetEnumerator(); 
    } 

    public IEnumerable<StateObservable> GetAll() 
    { 
     return _items.Concat(_deleted); 
    } 

    //... 
} 

注意該類型T必須從StateObservable導出。

現在,我深深地思考着。我會留下「爲什麼」的細節,並告訴你我目前在哪裏。我需要檢查我的型號上的特定屬性是否爲ObservableStateCollection<T>,並使用foreach循環訪問方法GetAll()

目前,我在:

if(prop.PropertyType.GetGenericTypeDefinition() == typeof(ObservableStateCollection<>)) 
{ 
     var collection = (ObservableStateCollection<StateObservable>)prop.GetValue(model, null); 
     foreach (var e in collection.GetAll()) 
     { 
      //act on ObservableStateCollection<StateObservable>      
     } 
} 

會拋出就行var collection = ...個例外,因爲我不能投ObservableStateCollection<DerivedType>ObservableStateCollection<BaseType>

什麼是我選擇這裏?如何獲得一個強類型對象,我可以撥打GetAll

回答

0

啊,明白了。我通過反思調用了GetAll。不知道爲什麼起初我沒有想到:

if(prop.PropertyType.GetGenericTypeDefinition() == typeof(ObservableStateCollection<>)) 
{       
    MethodInfo m = prop.PropertyType.GetMethod("GetAll"); 
    var collection = m.Invoke(prop.GetValue(model, null), null); 

    foreach (var e in (IEnumerable)collection) 
    { 
     \\act on item in collection      
    } 
}