Question

In my VB.NET application, I would like to move some code (a class) into a separate file. The separate file will use functions located in the main project.

If I create a Class Library, functions called from the DLL are not defined in the DLL and Visual Studio won't compile it.

In what ways could I move code into file and load/execute it at runtime and get the result the my main code? I don't know if I'm clear...

Était-ce utile?

La solution 2

Simple answer is - you can't.

You can't have assemblyA referencing assemblyB and assemblyB referencing assemblyA

The solution is probably to move any code that is used by both your application and assembly into the assembly. Then both can access this code

Autres conseils

This can be done indirectly using interfaces. Create a public interface in the library that has the calls you need to make against that main project's class. Have the main project's class implement this interface. When the main projects starts have it pass in instance of this class in to the library project via the interface. The library should store this reference. It can now makes calls against the main projects class using this reference through the interface.

The Library Project:

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

The Main Project:

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

This example has the library project using a class that is defined in the Main project.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top