dimanche 26 avril 2015

c# Reflection create instance of interface with generic

Is it possible via reflection to create an instance of an interface that has a generic, with both the generic and object type dynamically set?

public interface IRead<T>
{
    IList<T> Map();
}

public class FooRead : IRead<Bar>
{
    public IList<Bar> MapFile()
    {
        return new List<Bar>();
    }
}

So I want to set Foo and Bar dynamically at run time, and if possible keep the object strongly typed.

Ive got the interface type with its generic working, but cant figure out how to assign the dynamic object type

    var barType = Type.GetType("Bar");
    var reader = typeof(IRead<>);
    Type[] typeArgs = {barType}
    var readerInit = reader.MakeGenericType(typeArgs)

Additionally I got the interface set to a dynamic object

   var fooType = Type.GetType("FooRead");
   var reader = (IRead<Bar>)Activator.CreateInstance(fooType);

Havent figured out how to get both of these pieces together..





Aucun commentaire:

Enregistrer un commentaire