0

所以这是我的设置,评论显示了我想要做的事情:

class Process
{
    void SomeMethod()
    {
        // Here I want to call Parent.MethodToCall()
    }
}

class Controller
{
    Process c = new Process();

    void MethodToCall()
    {
    }
}

现在Controller.MethodToCall()将在整个类的生命周期中多次调用Process

它只是需要调用的父方法,所以我相信使用 anevent会有点浪费,因为我永远不会删除处理程序并且只会有一次调用。

所以我目前用来解决这个问题的方式如下:

class Process
{
    public Func<void> Method { get; set; }

    void SomeMethod()
    {
        Method();
    }
}

class Controller
{
    Process c = new Process() { Method = MethodToCall }

    void MethodToCall()
    {
    }
}

首先,语法可能不完美,我很快在记事本中敲了它。

我的问题:什么是实现我想要的最佳方式,因为我正在做的事情看起来很混乱?......或者我在设计方面是否认为这是完全错误的方式?

本质上,我想要做的是调用 Controller 类中的方法而不将其公开,因为如果它是公开的,我可以简单地将 Controller 作为参数传递给 Process。

4

4 回答 4

3
class Child
{
    Parent parent=null;
    public Child(Parent p)
    {
      parent=p;
    }
    void SomeMethod()
    {           
        parent.MethodToCall();
    }
}
于 2013-03-21T16:19:59.440 回答
2

这应该是如何做到这一点的一个很好的例子

class Child : Parent
{
    private void SomeMethod()
    {
        base.MethodToCall();
    }
}

class Parent
{
    Child c = new Child();

    protected void MethodToCall()
    {
        c.MethodToCall();//not sure if you are wanting to call c.MethodToCall();
    }
}
于 2013-03-21T16:28:34.303 回答
1

好吧,用 OOP 术语来说,正确的答案如下:

class Child : Parent
{
    void SomeMethod()
    {
        base.MethodToCall();
    }
}

class Parent
{
    protected void MethodToCall()
    {
       // protected methods are accesible from
       // descendants and private from outside
    }
}

但是你总是可以避免继承,使用聚合

于 2013-03-21T16:21:50.933 回答
0

你所做的基本上是滚动你自己的事件。在内部,事件处理程序只是附加到事件的委托,唯一的区别是只有事件的所有者才能引发它。

于 2013-03-21T16:21:17.883 回答