Mr *_* M. 4 c# delegates function-pointers
让我们班A有私有方法f()和g().让班级B有公共方法h.是否可以将指针/委托A.g从方法A.f指向B.h?
请考虑以下代码:
Class B
{
public B() {}
public h(/*take pointer/delegate*/)
{
//execute method from argument
}
}
Class A
{
private int x = 0;
private void g()
{
x = 5;
}
private void f()
{
B b = new B();
b.h(/*somehow pass delegate to g here*/);
}
}
Run Code Online (Sandbox Code Playgroud)
之后A.f()叫我想A.x是5.可能吗?如果是这样,怎么样?
您可以Action为方法创建一个参数:
public h(Action action)
{
action();
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用它:
b.h(this.g);
Run Code Online (Sandbox Code Playgroud)
可能值得注意的是,有一些泛型版本Action代表带参数的方法.例如,a Action<int>将使用单个int参数匹配任何方法.