2011-10-26 103 views
2

我在Host類,看起來像這樣實現的接口:思考:調用方法,傳遞一個委託作爲參數

void Method1(Action<Args1> action1, Action<Args1> action2); 

,然後我已被傳遞爲action1action2以下方法。

private void Action1(Args1 obj) 
{ 
//... 
} 

private void Action2(Args1 obj) 
{ 
//... 
} 

使用反射,我怎麼跟調用它,並通過方法Action1Action2

+0

爲什麼你想用反射來完成這個?還有哪些類型是在Action1和Action2中聲明的? – Ani

+0

@Ani我使用反射,所以我的插件將向後兼容;如果無法從基本程序集反映出來,它將不會執行Method1。 – sjlewis

回答

5
//here you pass the methods Action1 and Action2 as parameters 
//to the delegates - if you need to construct these by reflection 
//then you need to reflect the methods and use the 
//Delegate.CreateDelegate method. 
var param1 = new Action<Args1>(Action1); 
var param2 = new Action<Args1>(Action2); 
//instance of Host on which to execute 
var hostInstance = new Host(); 
var method = typeof(Host).GetMethod("Method1", 
    BindingFlags.Public | BindingFlags.Instance); 

method.Invoke(hostInstance, new object[] { param1, param2 });