I played, partially reinventing the wheels, so that I could understand how circles spin.
Consider this general function to compile and return the default constructor for a type.
public static Func<TConcrete> Creator<TConcrete>()
{
var ctor = typeof(TConcrete).GetConstructor(new Type[0]);
var lambda = Expression.Lambda<Func<TConcrete>>(Expression.New(ctor));
return lambda.Compile();
}
I believe this will return me a good typed delegate, which I can use to instantiate the past type.
Now consider if I want a function that will do this for a set of different types, how would I do it? I yearned for the lines ...
public static IEnumerable<Delegate> Creators(IEnumerable<Type> types)
{
foreach (var type in types)
{
var ctor = type.GetConstructor(new Type[0]);
var lamda = Expression.Lambda<Func<????>>(Expression.New(ctor));
yield return lambda.Compile();
}
}
As you can see from ????, I'm stuck here. Is there a way to do this or is my approach just messed up?
source
share