当另一个类只知道超类时,如何访问子类?

Joh*_*mBF 1 c# oop class object winforms

我有一个C#Windows Forms Application form1.cs,带有一个名为class1.cs的类库(DLL).现在在UI端我执行以下操作:

using System;
...
using System.Windows.Forms;
using ClassLibrary1;

namespace UI
{
    public partial class Form1 : Form
    {
        MyLibraryClass mlc = null;

        public Form1()
        {
            InitializeComponent();
            mlc = new MyLibraryClass(this);
        }

        public void aMethod() {
            Console.Write("Test");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在类库中我使用Form引用并想要在其中调用该方法,但我无权访问它:

...
using System.Windows.Forms;

namespace ClassLibrary1
{
    public class MyLibraryClass
    {
        private Form _form;

        public MyLibraryClass(Form form)
        {
            this._form = form;
            this._form.aMethod(); //Not working!
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我理解的原因是我的ClassLibrary1只知道Form但不知道Form1,因此不能从Form1调用方法.问题是,UI知道类库,但不是相反,因为这会产生一个环依赖,你当然知道.但是我该如何解决这个问题呢?

adr*_*dar 5

相反,Form你可以创建一个接口.

public interface IMyInterface {
    void aMethod();
} 
Run Code Online (Sandbox Code Playgroud)

Form1实现我们创建的接口

public partial class Form1 : Form, IMyInterface
{
    MyLibraryClass mlc = null;

    public Form1()
    {
        InitializeComponent();
        mlc = new MyLibraryClass(this);
    }

    public void aMethod() {
        Console.Write("Test");
    }
} 
Run Code Online (Sandbox Code Playgroud)

MyLibraryClass现在,你将取决于界面不是形式.这种方式MyLibraryClass可以使用任何尊重合同的形式,我们确保MyClassLibrary永远不会通过任何入侵者形式.

public class MyLibraryClass
{
    private IMyInterface _form;

    public MyLibraryClass(IMyInterface form)
    {
        this._form = form;
        this._form.aMethod(); // now is work :)
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 该接口将在类库项目中MyClassLibrary创建(在何处创建).

  2. 我建议你看看SOLID原理.

  • @Ian你应该查看界面是什么......这是C#和编程的好习惯(winforms与此无关) - 编写良好的WinForms项目将使用接口,就像任何其他编写良好的C#项目一样.你的下一个要点应该是学习坚实的原则. (2认同)