如何使用null目标创建实例方法的委托?

the*_*oop 8 .net c# delegates

我注意到Delegate类有一个Target属性,(可能)返回委托方法将执行的实例.我想做这样的事情:

void PossiblyExecuteDelegate(Action<int> method)
{
    if (method.Target == null)   
    {
        // delegate instance target is null
        // do something
    }
    else
    {
         method(10);
         // do something else
    }
}
Run Code Online (Sandbox Code Playgroud)

在调用它时,我想做类似的事情:

class A
{
    void Method(int a) {}

    static void Main(string[] args)
    {
        A a = null;
        Action<int> action = a.Method;
        PossiblyExecuteDelegate(action);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试构造委托时,我得到一个ArgumentException(委托给一个实例方法不能有一个null'this').我想做的是什么,我该怎么做?

the*_*oop 15

啊啊!找到了!

您可以使用CreateDelegate重载创建一个打开的实例委托,使用一个委托,该委托具有显式指定的隐式'this'第一个参数:

delegate void OpenInstanceDelegate(A instance, int a);

class A
{
    public void Method(int a) {}

    static void Main(string[] args)
    {
        A a = null;
        MethodInfo method = typeof(A).GetMethod("Method");
        OpenInstanceDelegate action = (OpenInstanceDelegate)Delegate.CreateDelegate(typeof(OpenInstanceDelegate), a, method);

        PossiblyExecuteDelegate(action);
    }
}
Run Code Online (Sandbox Code Playgroud)