最好通过代码来解释。我有一个通用类,其中有一个返回整数的方法。为了说明,这里是一个简单版本...
public class Gen<T>
{
public int DoSomething(T instance)
{
// Real code does something more interesting!
return 1;
}
}
在运行时,我使用反射来发现某个东西的类型,然后想要为该特定类型创建我的Gen类的实例。这很容易,可以像这样完成...
Type fieldType = // This is the type I have discovered
Type genericType = typeof(Gen<>).MakeGenericType(fieldType);
object genericInstance = Activator.CreateInstance(genericType);
我现在想创建一个表达式,它将以泛型类型实例作为参数,然后调用该类型的DoSomething方法。因此,我希望表达式有效地执行以下操作...
int answer = genericInstance.DoSomething(instance);
除了我在运行时某个时间点才有“实例(instance)”,而泛型实例(genericInstance)是如上所示的生成类型。我尝试创建Lambda表达式的方式如下...
MethodInfo mi = genericType.GetMethod("DoSomething",
BindingFlags.Instance | BindingFlags.Public);
var p1 = Expression.Parameter(genericType, "generic");
var p2 = Expression.Parameter(fieldType, "instance");
var x = Expression.Lambda<Func<genericType, fieldType, int>>
(Expression.Call(p1, mi, p2),
new[] { p1, p2 }).Compile();
...这样以后我就可以像这样调用它...
int answer = x(genericInstance, instance);
当然,您无法为 Func 提供实例参数,因此我不知道如何对 Lambda 生成进行参数化。有什么想法吗?