如何创建一个委托实例方法与空目标? [英] How to create a delegate to an instance method with a null target?

查看:250
本文介绍了如何创建一个委托实例方法与空目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注意到,委托类有一个目标属性,即(presumably)返回实例的委托方法将执行上。我想要做这样的事情:

I've noticed that the Delegate class has a Target property, that (presumably) returns the instance the delegate method will execute on. I want to do something like this:

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

在调用它,我想做的事情是这样的:

When calling it, I want to do something like:

class A
{
    void Method(int a) {}

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

不过,我得到一个ArgumentException(代表实例方法不能为空本),当我试图建立的委托。就是我想要做的可能,我该怎么办呢?

But I get an ArgumentException (Delegate to an instance method cannot have a null 'this') when I try to construct the delegate. Is what I want to do possible, and how can I do it?

推荐答案

AHAH! 找到了!

您可以使用 CreateDelegate 过载,使用委托与隐显式地指定这'第一个参数:

You can create an open instance delegate using a CreateDelegate overload, using a delegate with the implicit 'this' first argument explicitly specified:

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);
    }
}

这篇关于如何创建一个委托实例方法与空目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆