【问题标题】:Finding an ObservableCollection for given/dynamic type via reflection通过反射查找给定/动态类型的 ObservableCollection
【发布时间】: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


【解决方案1】:

比较属性的类型时,您似乎需要在 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)

【讨论】:

  • 谢谢,但似乎编译器不接受没有 T-argument 的 typeof(ObservableCollection) 的使用
  • @MartinTausch,我进行了编辑。我忘了为泛型类型添加尖括号。
  • 啊,好吧。现在我可以编译了。但是他仍然不接受返回值声明中的T。我可以作为对象返回,但不知道如何正确转换......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多