[英]Assign method to delegate through reflection
在通過反射動態地將方法分配給委托實例時,我陷入困境。 以下是我所面臨的情況的示例情景。
class Program
{
static void Main(string[] args)
{
new DynamicDelegateTest().Test();
}
}
public class DynamicDelegateTest
{
public void Test()
{
//This is what i target to do through reflection
ABC objABC1 = new ABC();
objABC1.Proc = Debugger;
objABC1.Test("Helloz");
//Implementing the same code through reflection
ABC objABC = new ABC();
MethodInfo MIDebugger = GetType().GetMethod("Debugger", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo MyProc = objABC.GetType().GetField("Proc", BindingFlags.Public | BindingFlags.Instance);
//This is the point where I got stuck up
MyProc.SetValue(objABC, MIDebugger);
objABC.Test("QWERTY");
}
void Debugger(object Tests)
{
Console.WriteLine(Tests);
}
}
public class ABC
{
public delegate void Delg(object P1);
public Delg Proc;
public void Test(object Tst)
{
if (Proc != null) Proc(Tst);
}
}
請幫忙。
您需要使用Delegate.CreateDelegate
來獲取委托實例,而不是方法信息。 對於非靜態方法,這還包括目標實例。 在這種情況下:
object del = Delegate.CreateDelegate(MyProc.FieldType, this, MIDebugger);
MyProc.SetValue(objABC, del);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.