这有点快
static Func<object, object[], object> BuildCaller(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object));
var pars = Expression.Parameter(typeof(object[]));
var pars2 = method.GetParameters();
var casted = new Expression[pars2.Length];
for (int i = 0; i < pars2.Length; i++)
{
casted[i] = Expression.Convert(Expression.ArrayAccess(pars, Expression.Constant(i)), pars2[i].ParameterType);
}
var call = Expression.Call(Expression.Convert(obj, method.DeclaringType), method, casted);
var cast = Expression.Convert(call, typeof(object));
var lamdba = Expression.Lambda<Func<object, object[], object>>(cast, obj, pars);
return lamdba.Compile();
}
static Func<object, object[], object> BuildCaller(FieldInfo field)
{
var obj = Expression.Parameter(typeof(object));
var pars = Expression.Parameter(typeof(object[]));
var call = Expression.Field(Expression.Convert(obj, field.DeclaringType), field);
var cast = Expression.Convert(call, typeof(object));
var lamdba = Expression.Lambda<Func<object, object[], object>>(cast, obj, pars);
return lamdba.Compile();
}
static Func<object, object[], object> BuildCaller(PropertyInfo property)
{
var obj = Expression.Parameter(typeof(object));
var pars = Expression.Parameter(typeof(object[]));
var pars2 = property.GetIndexParameters();
var casted = new Expression[pars2.Length];
for (int i = 0; i < pars2.Length; i++)
{
casted[i] = Expression.Convert(Expression.ArrayAccess(pars, Expression.Constant(i)), pars2[i].ParameterType);
}
var call = Expression.Property(Expression.Convert(obj, property.DeclaringType), property, casted);
var cast = Expression.Convert(call, typeof(object));
var lamdba = Expression.Lambda<Func<object, object[], object>>(cast, obj, pars);
return lamdba.Compile();
}
我创建了一个Expression
预缓存方法的委托(通过 s)。如果Arguments
是“固定的”,您可以更进一步,甚至预先缓存它们的转换(每次调用该方法时都会完成转换)
这是方法的示例。对于属性和字段,它是相似的(对于字段,它更容易)。
以及使用示例
var fun = BuildCaller(typeof(MyClass).GetMethod("MyMethod"));
var mc = new MyClass();
fun(mc, new object[] { 1, 2.0 });
您必须与您的缓存fun
一起Method