2010-08-24 96 views
1

我在vb.net 2008項目中使用下面的代碼動態加載dll的(與表單)從一個文件夾中,所有的偉大的作品,但我無法弄清楚的生活我如何調用一個函數或從插件獲取一個公共變量。vb.net動態插件加載問題

任何人都可以回答這個問題嗎?

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) 

回答

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 
+0

這讓我在正確的道路上,謝謝! – Joe 2010-08-24 22:28:18