2014-05-01 46 views
1

在我的VB.NET應用程序中,我想將一些代碼(一個類)移動到一個單獨的文件中。單獨的文件將使用位於主項目中的函數。類庫可以使用主項目中存儲的函數嗎?

如果我創建一個類庫,DLL中調用的函數沒有在DLL中定義,Visual Studio也不會編譯它。

我可以通過什麼方式將代碼移動到文件中,並在運行時加載/執行它,並將結果作爲我的主代碼?我不知道我是否清楚...

回答

0

簡單的答案是 - 你不能。

你不能有assemblyA引用assemblyBassemblyB引用assemblyA

的解決方案可能是移動所使用的兩個應用程序,並組裝成組件中的任何代碼。然後雙方都可以訪問此代碼

1

這可以通過接口間接完成。在庫中創建一個公共接口,該接口具有您需要針對該主項目類進行的調用。主項目的類實現這個接口。當主項目開始時,它通過接口將這個類的實例傳遞給庫項目。圖書館應該存儲這個參考。它現在可以通過界面使用此引用對主要項目類進行調用。

圖書館計劃:

Public Interface ITimeProvider 
    ReadOnly Property Time As Date 
End Interface 

Public Class LibraryClass 
    Private Shared _timeProvider As ITimeProvider 

    Public Shared Sub Init(timeProvider As ITimeProvider) 
     _timeProvider = timeProvider 
    End Sub 

    Public Function GetTimeString() As String 
     Return "The current time is " & _timeProvider.Time.ToString 
    End Function 
End Class 

主營項目:

Public Class SimpleTimeProvider 
    Implements ClassLibrary1.ITimeProvider 

    Public ReadOnly Property Time As Date Implements ClassLibrary1.ITimeProvider.Time 
     Get 
      Return Date.Now 
     End Get 
    End Property 
End Class 

Public Class MainClassTest 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load 
     ClassLibrary1.LibraryClass.Init(New SimpleTimeProvider) 

     Dim test As New ClassLibrary1.LibraryClass 
     Console.WriteLine(test.GetTimeString) 
    End Sub 
End Class 

此示例使用在主項目中定義一個類的庫項目。

+0

有趣的解決方法! – Velcro

+0

有時候它可能是一個有用的模式,但是有很多代碼,它也可能很難遵循。這真的取決於你是否真的值得額外的努力和複雜性。 –

相關問題