gpt4 book ai didi

c# - 如何为具有空目标的实例方法创建委托(delegate)?

转载 作者:太空狗 更新时间:2023-10-29 18:15:44 24 4
gpt4 key购买 nike

我注意到 Delegate 类有一个 Target 属性,它(大概)返回委托(delegate)方法将在其上执行的实例。我想做这样的事情:

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

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

class A
{
void Method(int a) {}

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

但是当我尝试构造委托(delegate)时,我得到了一个 ArgumentException(委托(delegate)给实例方法不能有一个空的“this”)。我想做的事是否可行,我该怎么做?

最佳答案

啊哈! found it!

您可以使用 CreateDelegate 创建一个开放实例委托(delegate)重载,使用带有显式指定的隐式“this”第一个参数的委托(delegate):

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

关于c# - 如何为具有空目标的实例方法创建委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/951624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com