How to load an internal class in end-user compiled code ? (advanced)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 03:40:27

问题


I have a main program with two classes

1- A winform that contains two elements :

  • Memo Edit to type some code;
  • Button named compile.

The end user may type some VB.Net code in the memo edit and then compile it.

2 - A simple test class :

Code :

Public Class ClassTest
    Public Sub New()
        MsgBox("coucou")
    End Sub
End Class

Now I would like to use the class ClassTest in the code that will be typed in the MemoEdit and then compile it :

When hitting compile I recieve the error :

The reason is that, the compiler can't find the namespace ClassTest

So to summarize :

  • The class ClassTest is created in the main program
  • The end user should be able to use it and create a new assembly at run time

Does anyone know how to do that please ?

Thank you in advance for your help.

Code of the WinForm :

Public Class Form1
    Private Sub SimpleButtonCompile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButtonCompile.Click
        Dim Code As String = Me.MemoEdit1.Text

        Dim CompilerResult As CompilerResults
        CompilerResult = Compile(Code)
    End Sub

    Public Function Compile(ByVal Code As String) As CompilerResults
        Dim CodeProvider As New VBCodeProvider
        Dim CodeCompiler As System.CodeDom.Compiler.CodeDomProvider = CodeDomProvider.CreateProvider("VisualBasic")

        Dim Parameters As New System.CodeDom.Compiler.CompilerParameters
        Parameters.GenerateExecutable = False

        Dim CompilerResult As CompilerResults = CodeCompiler.CompileAssemblyFromSource(Parameters, Code)

        If CompilerResult.Errors.HasErrors Then
            For i = 0 To CompilerResult.Errors.Count - 1
                MsgBox(CompilerResult.Errors(i).ErrorText)
            Next

            Return Nothing
        Else
            Return CompilerResult
        End If
    End Function
End Class

回答1:


Here is the solution :

If the end user wants to use internal classes he should use the command : Assembly.GetExecutingAssembly

The full code will be :

Code :

Imports System.Reflection
Imports System

Public Class EndUserClass
    Public Sub New()

        Dim Assembly As Assembly = Assembly.GetExecutingAssembly
        Dim ClassType As Type = Assembly.GetType(Assembly.GetName().Name & ".ClassTest")
        Dim Instance = Activator.CreateInstance(ClassType)

    End Sub 
End class


来源:https://stackoverflow.com/questions/22379406/how-to-load-an-internal-class-in-end-user-compiled-code-advanced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!