如何在运行时加载类库 DLL 并使用 VB.NET 运行类函数? [英] How do I load a Class Library DLL at runtime and run a class function using VB.NET?
问题描述
假设我在名为 SomeClass 的类库项目中有一个这样的类-
Say I've a class like this inside a class library project called SomeClass-
Public Class SomeClass
Public Function DoIt() as String
Return "Do What?"
End Function
End Class
我得到一个 SomeClass.dll
,我想在运行时从另一个 Windows 窗体应用程序加载它,然后让它调用 DoIt()
函数并显示它的值在消息框或其他东西中.我该怎么做?
I get a SomeClass.dll
which I want to load at runtime from another Windows Forms Application, and then have it call the DoIt()
function and show it's value in a messagebox or something. How do I do that?
推荐答案
我建议让 DoIt
共享,因为它不需要类状态:
I suggest to make DoIt
shared, since it does not require class state:
Public Class SomeClass
Public Shared Function DoIt() as String
Return "Do What?"
End Function
End Class
然后调用它很容易:
' Loads SomeClass.dll
Dim asm = Assembly.Load("SomeClass")
' Replace the first SomeClass with the base namespace of your SomeClass assembly
Dim type = asm.GetType("SomeClass.SomeClass")
Dim returnValue = DirectCast(type.InvokeMember("DoIt", _
BindingFlags.InvokeMethod | BindingFlags.Static, _
Nothing, Nothing, {}),
String)
如果您无法共享该方法,您可以使用 Activator.CreateInstance 并将其作为参数传递给 Type.InvokeMember.
If you cannot make the method shared, you can create an instance of your class with Activator.CreateInstance and pass it as a parameter to Type.InvokeMember.
我所有的代码示例都假设 Option Strict On 和 Option Infer On.
这篇关于如何在运行时加载类库 DLL 并使用 VB.NET 运行类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!