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.