Expression Lambda

利用 Expression 创建无参实例

public static T New<T>()
{
    Type t = typeof( T );
    BlockExpression blockExpression = Expression.Block( t, Expression.New( t ) );
    Expression<Func<T>> exp = Expression.Lambda<Func<T>>( blockExpression );
    Func<T> method = exp.Compile();
    return method();
}

利用 Expression 创建有参实例

private static ObjectActivator<T> GetActivator<T>(ConstructorInfo ctor)
{
    ParameterInfo[] paramsInfo = ctor.GetParameters();

    //create a single param of type object[]
    ParameterExpression param = Expression.Parameter(typeof(object[]), "args");

    var argsExp = new Expression[paramsInfo.Length];

    //pick each arg from the params array 
    //and create a typed expression of them
    for (int i = 0; i < paramsInfo.Length; i++)
    {
        Expression index = Expression.Constant(i);
        Type paramType = paramsInfo[i].ParameterType;
        Expression paramAccessorExp = Expression.ArrayIndex(param, index);
        Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);
        argsExp[i] = paramCastExp;
    }

    //make a NewExpression that calls the ctor with the args we just created
    NewExpression newExp = Expression.New(ctor, argsExp);

    //create a lambda with the New Expression as body and our param object[] as arg
    LambdaExpression lambda = Expression.Lambda(typeof(ObjectActivator<T>), newExp, param);
    Console.WriteLine(lambda);
    return (ObjectActivator<T>)lambda.Compile();
}

调用
ConstructorInfo ctor = typeof(People).GetConstructors().First();
ObjectActivator<Created> peopleActivator= GetActivator<People>(ctor);
Peopleinstance = peopleActivator(123, "Roger");

link: https://vagifabilov.wordpress.com/2010/04/02/dont-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容