只是为了让您知道术语,您正在寻找“Inversion of Control”或“IoC”。
有多种实现方式,包括Dependency Injection 和 Nico 的回答中的回调(例如委托)。还有服务定位器(尽管许多人认为这是一种“反模式”)和工厂。
就个人而言,我更喜欢依赖注入方法:
基本上,您的 DLL(又名“class library”)需要一个可以执行功能的对象,但它需要其他人(调用者)来实现实际逻辑。
因此,您只需在 DLL 中创建一个接口,该接口定义您需要的对象类型:
Namespace DLL
Public Interface IDataRetriever
Public Function GetData() As Object
End Interface
End Namespace
然后在引用您的 DLL 的 MainForm 项目中,只需创建一个实现此接口的类:
Public Class DataRetriever
Implements DLL.IDataRetriever
Public Function GetData() As Object Implements DLL.IDataRetriever.GetData
//...
Return New Object()
End Function
End Class
(请注意,任何类都可以实现接口,包括已经存在的类甚至 MainForm 本身。您不需要仅为接口创建新类 - 但请确保你正在关注separation of concerns。)
现在,当您调用 DLL 时,您可以将 DataRetriever 传递给它,您的 DLL 就会知道它在处理什么。
Namespace DLL
Public Class Utility
Public Shared Function DLLFunction( retriever as IDataRetriever )
retriever.GetData()
End Function
End Class
End Namespace
Class MainForm
Sub Example()
DLL.Utility.DLLFunction( New DataRetriever() )
End Sub
End Class