我在vb.net 2008项目中使用以下代码从文件夹动态加载dll(带表单),一切都很好但是我无法弄清楚如何调用函数或从插件中获取一个公共变量。
任何人都可以为我解答这个问题吗?
Dim PluginList As String() = Directory.GetFiles(appDir, "*.dll")
For Each Plugin As String In PluginList
Dim Asm As Assembly
Dim SysTypes As System.Type
Asm = Assembly.LoadFrom(Plugin)
SysTypes = Asm.GetType(Asm.GetName.Name + ".frmMain")
Dim IsForm As Boolean = GetType(Form).IsAssignableFrom(SysTypes)
If IsForm Then
Dim tmpForm As Form = CType(Activator.CreateInstance(SysTypes), Form)
答案 0 :(得分:1)
您应该在公共程序集中创建一个接口并让表单实现它,这样您就可以将动态加载的对象转换为接口类型。
Imports System.Reflection
Imports Plugin.Interfaces
Sub Main()
Dim assembly As Assembly
assembly = assembly.LoadFrom("Plugin.X.dll")
Dim type As Type
Dim found As Boolean = False
For Each type In assembly.GetTypes()
If GetType(IForm).IsAssignableFrom(type) Then
found = True
Exit For
End If
Next
If found Then
Dim instance As IForm
instance = CType(Activator.CreateInstance(type), IForm)
Console.WriteLine(instance.Add(20, 20))
End If
End Sub
界面装配
Public Interface IForm
Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
End Interface
插件程序集
Imports Plugin.Interfaces
Public Class Form
Implements IForm
Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Implements IForm.Add
Return x + y
End Function
End Class