[英]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.