Finding an ObservableCollection for given/dynamic

2019-07-17 06:51发布

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条回答
老娘就宠你
2楼-- · 2019-07-17 07:05

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)
查看更多
登录 后发表回答