【发布时间】:2014-02-14 14:36:51
【问题描述】:
我有一个包含不同类型的多个 ObservableCollections 的类。现在,我想通过反射为给定类型找到正确的 Collection,因为我不想构建一个 if-monster,每次添加另一个 Collection 时我都必须更新它。
这个方法是第一步:
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;
}
任何想法如何实现这一点?
更新:
一个可行的解决方案:
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 足以添加和删除。
【问题讨论】:
-
你能不能只根据我更新的答案添加一个显式转换并将返回类型保留为 ObservableCollection
? -
似乎编译器不接受 'ObservableCollection
' 作为返回类型,只要方法调用没有提供
标签: c# generics reflection types observablecollection