Finding an ObservableCollection for given/dynamic type via reflection

僤鯓⒐⒋嵵緔 提交于 2019-12-12 19:00:06

问题


I have a Class with several ObservableCollections for different types. Now, I want to find the correct Collection for a given type via reflection, because I don't want to build an if-monster which I have to update every time I add another Collection.

This method was the first step:

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;

}

Now, I need a second method, which accepts a concrete object as parameter and finds the correct Collection. Somehow like this:

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;

}

Any ideas how to realize this?

Update:

A working solution:

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;

}

This will return the correct collection as object. I still don't know how to cast to the correct generic type, but casting to IList is enough for adding and removing.


回答1:


When comparing the type of the property, it looks like you need to add a call to MakeGenericType() on the ObservableCollection type. Haven't tested this but maybe something like...

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;

}

Edit To avoid overhead boxing with value types, the above method definition could be improved by changing the parameter type from object to type T

public ObservableCollection<T> GetObservableCollectionFor(T sObject)


来源:https://stackoverflow.com/questions/21782154/finding-an-observablecollection-for-given-dynamic-type-via-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!