让我们使用私有(private)方法f()
和g()
类A
。让类 B
有公共(public)方法 h
。是否可以将指向 A.g
的指针/委托(delegate)从方法 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*/);
}
}
调用 A.f()
后,我希望 A.x
为 5
。是否可以?如果是,怎么办?
最佳答案
您可以创建一个 Action
方法的参数:
public h(Action action)
{
action();
}
然后这样调用它:
b.h(this.g);
可能值得注意的是 Action
有通用版本表示带有参数的方法。例如,Action<int>
会将任何方法与单个 int
匹配参数。
关于c# - 委托(delegate)给私有(private)函数作为不同类中方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30361288/