文号
t50167
阅读
6403
回复
4
收藏
3
用XXXXXX(代码翻自C#) 实现动态编译
2012/08/31
IP:广东
动态编译可以理解为,程序在执行过程中编译一段代码并把编译之后的结果作为程序的一部分运行。

效果:
QQ截图20120831013415.jpg
如果你对VB语法有了解,可以尝试修改代码,并观察输出的结果。
编译好的程序在RTC\bin\release 文件夹下,可以直接运行。

源代码附在zip包里。注释是英文写的,英文不好的兄弟我向您道个歉

QQ截图20120831014205.jpg
代码已经非常简洁了 。如果您没有Visual Studio 11(我用的版本),可以在VS2010 VS2008或者其他.NET环境下创建项目并复制窗体和代码。
attachment icon RTC.zip 72.85KB ZIP 18次下载
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
引用
评论
14年4个月前IP:未同步
446879
2楼
居然半夜三更发帖~~
-1
科创币
novakon
2012/08/31
一般来说,在茶话以外灌纯净水是不允许的。
引用
评论
14年2个月前IP:未同步
463564
3楼
回 楼主(novakon) 的帖子
您居然用VS2012?那灰糊糊一团的东西!!!
引用
评论
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的