利用 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/