如何在最终用户编译的代码中加载内部类?(先进的) [英] 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 :
原因是,编译器找不到命名空间ClassTest
The reason is that, the compiler can't find the namespace ClassTest
总结一下:
- 在主程序中创建了类 ClassTest
- 最终用户应该能够使用它并在运行时创建新程序集
有人知道怎么做吗?
预先感谢您的帮助.
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屋!