mardi 26 mai 2015

How to determine dynamically if type is an Interface using reflection?

For starters, this question is not a repeat of this post that I have read 100 times (please read on for question): How to determine if a type implements an interface with C# reflection

I'm using reflection to iterate through properties on objects dynamically at runtime to manipulate and add data. The root issue for me is naturally, you cannot instantiate an instance of an Interface and therefore my code using Activator.CreateInstance later downstream must not be ran against types found to be an Interface or a collection of an Interface type.

Say I have the following on an Person class:

public IList<Address> addresses1 {get ; set; } \\ This property **should** flag being an Interface public List<Address> addresses2 {get ; set; } \\ This property **should NOT** flag being an Interface

Using the following code while reflecting on the property I can find out if the property implements an Interface:

propertyTypeFromReflection.GetInterfaces().Any()

The problem I have is both IList<Address> and List<Address> have the statement above return true. That's because even List<T> as we know actually implements a slew of Interfaces (i.e. IList, ICollection, IEnumerable, etc.).

Since I am doing this investigation dynamically, I have no idea of how to test if my type implements a specific Interface like all the examples show such as the link I posted at the beginning which do the following:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType)) typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

I need help determining if the object Property reflected upon dynamically and in focus, is directly an Interface as opposed to a concrete type? All the examples require testing the known Interface to a known concrete type, but since this is happening dynamically I don't know how to accomplish this?





Aucun commentaire:

Enregistrer un commentaire