jeudi 4 janvier 2018

How to find the concrete type of interface instance when using reflection?

I'm currently trying to create an instance of an object that was defined as an interface. Specifically:

public static class A {
    public static IList<string> SampleList { get; set; }

    public void Initialize() { 
        SampleList = new List<string>();
    }
}

// In some other class
var propertyInfo = typeof(A).GetProperty("SampleList");
propertyInfo.PropertyType.GetConstructors().Any(); // false
// ^ I would like this to be true

When SampleList is instead typed as a List instead of the interface (IList) I'm able to produce a constructor and instantiate an instance of this list. I have the same luck with Arrays + other instances that aren't defined as an interface.

Something else I noticed is that when I use List, and invoke PropertyType.GetInterfaces() I get a list of 8 interfaces while when I invoke the same command using an IList instance I only get 3 interfaces. In general I'm getting a lot less information.

I was wondering if it was possible to find out the concrete class itself? If so, how?





Aucun commentaire:

Enregistrer un commentaire