Creating a compiled constructor expression with type type only

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>()
{
    // All checking removed for brevity
    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?

+5
source share
2 answers

Use non-original overload in combination with MakeGenericType:

var lamda = Expression.Lambda<Func<????>>(Expression.New(ctor));

It should become:

var funcType = typeof(Func<>).MakeGenericType(type);
var lamda = Expression.Lambda(funcType, Expression.New(ctor));
+6

Expression.Lambda, Type:

Type delegateType = typeof(Func<>).MakeGenericType(type);
var lambda = Expression.Lambda(delegateType, Expression.New(ctor));
yield return lambda.Compile();

, Lambda LambdaExpression , Expression<TDelegate> - a Compile, Delegate, . , " ".

+7

All Articles