gpt4 book ai didi

vb.net - 如何在运行时加载类库 DLL 并使用 VB.NET 运行类函数?

转载 作者:行者123 更新时间:2023-12-02 06:47:15 25 4
gpt4 key购买 nike

假设我在名为 SomeClass 的类库项目中有一个这样的类-

Public Class SomeClass
Public Function DoIt() as String
Return "Do What?"
End Function
End Class

我得到了一个 SomeClass.dll,我想在运行时从另一个 Windows 窗体应用程序加载它,然后让它调用 DoIt() 函数并显示它的值在消息框或其他东西中。我该怎么做?

最佳答案

我建议将 DoIt 共享,因为它不需要类状态:

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 .

我的所有代码示例均假设 Option Strict On 和 Option Infer On。

关于vb.net - 如何在运行时加载类库 DLL 并使用 VB.NET 运行类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15358788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com