novakon作者
14年4个月前IP:未同步
446873
1楼
源码

REM Dynamic Compilation Demo in VB
REM translated from the C# code found on Internet.
REM by Qin Yongliang, 20120831
REM feel free to use the code for any purpose

Imports System.CodeDom.Compiler

Imports Microsoft.VisualBasic
Imports Microsoft.CSharp
'optional.

Imports System.Reflection

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Button1.Text = "Compiling..."
        Me.Enabled = False
        Me.Refresh()

        Dim cpara = New CompilerParameters
        cpara.CompilerOptions = Trim(TextBox2.Text)
        'options like "/optimize" or whatever
        cpara.GenerateInMemory = True
        'stores the compile result in memory.
        cpara.IncludeDebugInformation = False 'we are unlikely to debug it

        'cpara.ReferencedAssemblies.Add("mscorlib.dll")
        'cpara.ReferencedAssemblies.Add("system.dll")
        'add references if needed.

        Dim cdp = CodeDomProvider.CreateProvider("VisualBasic")
        'self-explaining

        Dim res = cdp.CompileAssemblyFromSource(cpara, TextBox1.Text) 'show results

        'MsgBox(res.Errors(0).ToString)
        'check if errors occur.
        Dim asm = res.CompiledAssembly 'as System.Reflection.Assembly
        Dim newclass = asm.CreateInstance("newclass") 'create instance from compiled assembly
        Dim newclasstype = newclass.GetType

        Button1.Text = "Running..."
        Dim ret As Double = newclasstype.GetMethod("test").Invoke(newclass, Nothing)
        'assume the code returns a number; assume the code has no parameters("Nothing");
        Button1.Text = "Finished!"
        MsgBox(ret.ToString, , "Result of test()") 'show result of the invoked method
        Button1.Text = "Compile and Run"
        Me.Enabled = True
    End Sub
End Class
评论
文号 / 446873

万流景仰
名片发私信
学术分 16
总主题 1270 帖总回复 8407 楼拥有证书:学者 机友 笔友
注册于 2008/03/29 15:34:00最后登录 2022/01/09 14:09:34
主体类型:个人
所属领域:无
认证方式:手机号
IP归属地:0

个人简介

已走,勿送

笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的