2017-05-26 24 views
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代表。我究竟做錯了什麼?

回答

3

你可以這樣說:

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

OMG這個作品!謝謝一堆! –

相關問題