[英]Using delegate action and predicate as a argument for a method in a class
[英]Delegate to private function as argument for method in different class
讓我們用私有方法f()
和g()
來獲取A
類。 讓B
類有公共方法h
。 是否可以將指針/委托從方法Af
傳遞給Ag
到Bh
?
請考慮以下代碼:
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*/);
}
}
在調用Af()
后,我希望Ax
為5
。 可能嗎? 如果是這樣,怎么樣?
您可以為方法創建一個Action
參數:
public h(Action action)
{
action();
}
然后像這樣調用它:
b.h(this.g);
可能值得注意的是, Action
泛型版本表示帶參數的方法。 例如, Action<int>
將使用單個int
參數匹配任何方法。
是的。
class B
{
public B()
{
}
public void h(Action func)
{
func.Invoke();
// or
func();
}
}
class A
{
private int x = 0;
private void g()
{
x = 5;
}
private void f()
{
B b = new B();
b.h(g);
}
}
是的,這是可能的:
class B
{
public B() {}
public void h(Action a)
{
a();
}
}
class A
{
private int x = 0;
private void g()
{
x = 5;
}
private void f()
{
B b = new B();
b.h(g);
}
}
這是一個小提琴,表明它有效 - 為了示范目的,我改變了一些私人公共場所。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.