在运行时将lambda转换为委托

时间:2017-05-26 11:56:08

标签: c# lambda delegates runtime

我试图在运行时使用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委托。我做错了什么?

1 个答案:

答案 0 :(得分:3)

你可以这样做:

var lamda = Expression.Lambda<Progress>(call, value);
Progress compiled = lamda.Compile();