我有一个C#Windows窗体应用程序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");
}
}
}
在类库中,我接受了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!
}
}
}
据我了解,其原因是我的ClassLibrary1仅知道Form,但不知道Form1,因此无法从Form1调用方法。问题是,UI知道类库,但不知道类库,因为您会知道,这会创建环依赖。但是我该如何解决这个问题呢?
相反,Form
您可以创建一个界面。
public interface IMyInterface {
void aMethod();
}
Form1
将实现我们创建的接口
public partial class Form1 : Form, IMyInterface
{
MyLibraryClass mlc = null;
public Form1()
{
InitializeComponent();
mlc = new MyLibraryClass(this);
}
public void aMethod() {
Console.Write("Test");
}
}
在MyLibraryClass
现在,你将取决于界面不是形式。这种方式MyLibraryClass
可以使用尊重合同的任何形式,并且我们确保inMyClassLibrary
绝不会传递任何入侵者形式。
public class MyLibraryClass
{
private IMyInterface _form;
public MyLibraryClass(IMyInterface form)
{
this._form = form;
this._form.aMethod(); // now is work :)
}
}
笔记:
该接口将在“类库”项目中MyClassLibrary
创建(在此处创建)。
我建议您看一下SOLID原则。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句