2
我试图在运行时使用Expression
类的静态方法绑定委托。首先,以下两个任务在编译时工作:在运行时将lambda转换为委托
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
类这样的进步委托绑定:
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
代表。我究竟做错了什么?
OMG这个作品!谢谢一堆! –