Generics & reflection

G

Guest

Given a class 'Invoice' with a property 'public IMyColl<IInvoiceLine>
InvoiceLines' where 'IMyColl<T> : IList<T>' i would like to detect by
reflection that 'InvoiceLines' is a 'System.Collection.Generic.IList'.

When performing something like: 'if
(typeof(IList<>).IsAssignableFrom(propertyInfo.Type))' where 'propertyInfo'
obviously refers to the 'InvoiceLines', the result is always 'false' because
indeed 'IList<object>' and 'IMyColl<IInvoiceLine>' are not type-related.

So, I would like something that restricts the checking to the 'list' part of
the type 'IMyColl<IInvoiceLine>', but cannot find it when exploring the
different properties of 'propertyInfo.Type'.
 
G

Guest

Reflection doesn't provide an ImplementsInterface-type method that I'm aware
of. It might in 2.0. For 1.1 I would use the following code:

Type ifcType =
propertyInfo.Type.GetInterface("System.Collection.Generic.IList") or of
course you can always use the "is" operator if you have the actual property
object.

You could also use FindInterfaces but I think that it is overkill.

Don't know if that helps any.

Michael Taylor, MCP, MCAD - 6/23/05
 
G

Guest

Dear Michael, thank you.

1. question was asked for .NET 2.0 only (supports generics)
2. correction in my example: 'propertyInfo.Type' should have read
'propertyInfo.PropertyType'
3.1 result of trying your suggestion:
object o11 =
propertyInfo.PropertyType.GetInterface("System.Collections.IList");
object o12 =
propertyInfo.PropertyType.GetInterface("System.Collections.ICollection");
object o13 =
propertyInfo.PropertyType.GetInterface("System.Collections.IEnumerable");
object o21 =
propertyInfo.PropertyType.GetInterface("System.Collections.Generic.IList<>");
object o22 =
propertyInfo.PropertyType.GetInterface("System.Collections.Generic.ICollection<>");
object o23 =
propertyInfo.PropertyType.GetInterface("System.Collections.Generic.IEnumerable<>");
is: only 'o13' is not null.
3.2 this is indeed the correct outcome and confirms the absence of solution,
so far.
4.1 result of 'Type type in propertyInfo.PropertyType.GetInterfaces()':
System.Collections.Generic.IList`1[Xyz.Domn.Path.ProgDataT1+IInvoiceLines]

System.Collections.Generic.ICollection`1[Xyz.Domn.Path.ProgDataT1+IInvoiceLines]

System.Collections.Generic.IEnumerable`1[Xyz.Domn.Path.ProgDataT1+IInvoiceLines]
System.Collections.IEnumerable
4.2 this is indeed 'overkill', plus i find it a little akward to decode a
string representation "[...]`1[...]" to conclude that it contains something
like 'System.Collections.Generic.IList'; if i try to get the type of that
string, it would give me the type object but i am then probably back to
square one in testing for it being assignable from IList<>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top