我试图在运行时使用Expression
类的静态方法绑定委托。首先,以下两个赋值在编译时起作用:
public delegate void Progress(State value);
public enum State
{
}
public void DoStuff(int value)
{
}
...
Action<State> action = (State a) => { DoStuff((int)a); };
Progress actionDelegate = (State a) => { DoStuff((int)a); }; //this is what I'm trying to achieve
我尝试使用Expression
这样的类绑定Progress委托:
public void CreateDelegate()
{
var value = Expression.Variable(typeof(State), "a");
var castedValue = Expression.Convert(value, typeof(int));
var method = GetType().GetMethod("DoStuff");
var call = Expression.Call(Expression.Constant(this), method, castedValue);
var lamda = Expression.Lambda(call, value);
Progress compiled = (Progress)lamda.Compile(); //Invalid cast from Action<State> to Progress
}
Lambda.Compile
返回Action<State>
,但我需要Progress
委托。我做错了什么?
答案 0 :(得分:3)
你可以这样做:
var lamda = Expression.Lambda<Progress>(call, value);
Progress compiled = lamda.Compile();