繁体   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