如何在运行时加载类库DLL并使用VB.NET运行类函数? [英] How do I load a Class Library DLL at runtime and run a class function using VB.NET?
问题描述
public Class SomeClass
公共功能DoIt()as String
返回Do What?
结束函数
结束类
我得到一个 SomeClass.dll
我想在运行时从另一个Windows窗体应用程序加载,然后调用$ code> DoIt()函数并显示它的值在一个messagebox或某事。我如何做?
我建议使 DoIt
共享,因为它不需要类状态:
公共类SomeClass
公共共享函数DoIt()as String
返回做什么?
结束函数
结束类
然后调用很简单:
'加载SomeClass.dll
Dim asm = Assembly.Load(SomeClass)
'将SomeClass替换为SomeClass程序集的基本命名空间
Dim type = asm.GetType(SomeClass.SomeClass)
Dim returnValue = DirectCast(type.InvokeMember(DoIt _
BindingFlags.InvokeMethod | BindingFlags.Static,_
没有,没有,{}),
字符串)
如果您无法使该方法共享,您可以使用 Activator.CreateInstance 并将其作为参数传递给 Type.InvokeMember 。
我的所有代码示例假定选项严格打开和选项置入。
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
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?
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
Then calling it is easy:
' 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)
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.
All my code examples assume Option Strict On and Option Infer On.
这篇关于如何在运行时加载类库DLL并使用VB.NET运行类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!