簡體   English   中英

將類型強制轉換為特定的MyCollection <MyType> 並通過反射對其調用方法

[英]Cast type as specific MyCollection<MyType> and call method on it via Reflection

我有一個自定義集合類型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的強類型對象?

啊明白了。 我通過反射調用了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                      
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM