Reputation: 3979
I need to determine if a List contains ICollection where T is dynamic and not known at compiletime. Heres my code to better understand what I mean:
private void RefreshDataSource<T>(ICollection<T> dataSource) where T : IEquatable<T>
{
dynamic row = view.GetFocusedRow();
//Get's the focused row from a DevExpress-Grid
//I don't know the type because it's MasterDetail and the view can be a DetailView. In this case type T isn't the underlying type.
//Getting all Properties
var dummy = dataSource.FirstOrDefault();
var props = dummy.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
//Now comes the real problem, I need to determine the Detail Datasource
//and to do this I want to check if there is a Property from ICollection<typeof(row)>
//How can I check on ICollection<typeof(row)> instead of row
//IsAssignableFrom would better fit my needs but I don't get how to solve my problem with it.
var detailSource = props.FirstOrDefault(p => p.PropertyType.IsInstanceOfType(row));
}
The code is broken to the important points, so don't wonder if sth. doesn't makes sense in your eyes ;-). Is there any way to check on ICollection<T>
where T is a dynamic type and just know at runtime?
Notice that the given T on top of the method isn't the type of row, because of MasterDetail relationship!!!
UDPATE
I think I need to clarify what I need. Think of me as a Grid. I'm getting a DataSource which is a ICollection<T>
and every row is represented by an object of T. Now I'm using MasterDetail relationships so that T just represents one MasterRow in the Grid. The Rows of a DetailView are represented by any ICollection<AnyClass>
which is defined as a Property on T.
Now I need to determine this ICollection<AnyClass>
Property from T without knowing what AnyClass is at compile time. Because I know the DetailView I can do this:
dynamic row = view.GetFocusedRow();
So row is of type AnyClass and known at Runtime. But how can I find this ICollection<AnyClass>
Property in the PropertyCollection of T? This is my problem.
Upvotes: 1
Views: 133
Reputation: 9477
In general, this should do
.GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<dynamic>));
in case you meant T
and not dynamic
, simple replace them.
.GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<T>));
If you want T and subtypes of it, it gets more complicated
.GetType().GetInterfaces().Any(intf => intf.IsGenericType &&
intf.GetGenericTypeDefinition() == typeof(ICollection<>) &&
intf.GetGenericArguments()[0].IsAssigneableFrom(typeof(T)));
EDIT Since you calrified what you actually need:
.GetType().GetInterfaces().Any(intf => intf.IsGenericType &&
intf.GetGenericTypeDefinition() == typeof(ICollection<>));
It could be much simpler, but ICollection<T>
does not implement ICollection
.
Upvotes: 1