簡體   English   中英

委托私有函數作為不同類中方法的參數

[英]Delegate to private function as argument for method in different class

讓我們用私有方法f()g()來獲取A類。 B類有公共方法h 是否可以將指針/委托從方法Af傳遞給AgBh

請考慮以下代碼:

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()后,我希望Ax5 可能嗎? 如果是這樣,怎么樣?

您可以為方法創建一個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM