如何在最终用户编译的代码中加载内部类? (高级) [英] How to load an internal class in end-user compiled code ? (advanced)
问题描述
我有一个具有两个类的主程序
I have a main program with two classes
1-一个包含两个元素的winform:
1- A winform that contains two elements :
- 备注编辑以键入一些代码;
- 名为compile的按钮。
最终用户可以在备忘录编辑中键入一些VB.Net代码,然后进行编译。
The end user may type some VB.Net code in the memo edit and then compile it.
2-一个简单的测试类:
2 - A simple test class :
代码:
Public Class ClassTest
Public Sub New()
MsgBox("coucou")
End Sub
End Class
现在我想使用该类将在MemoEdit中键入然后进行编译的代码中的ClassTest:
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 :
< img src = https://i.stack.imgur.com/UBzhf.png alt =输入即时通讯这里的年龄描述>
原因是,编译器找不到命名空间ClassTest
The reason is that, the compiler can't find the namespace ClassTest
总结:
- ClassTest类是在主程序中创建的
- 最终用户应为能够在运行时使用它并创建新的程序集
有人知道如何做到这一点吗?
Does anyone know how to do that please ?
在此先感谢您的帮助。
WinForm的代码:
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
推荐答案
这是解决方案:
如果最终用户要使用内部类,则应使用以下命令: Assembly.GetExecutingAssembly
If the end user wants to use internal classes he should use the command : Assembly.GetExecutingAssembly
完整代码将为:
代码:
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
这篇关于如何在最终用户编译的代码中加载内部类? (高级)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!