您的位置:首页 > 编程语言 > VB

一个动态编译并运行C#或VB.NET代码的工具[翻译]

2005-10-08 22:05 1106 查看

原文地址
源码下载

简介
这个程序在内存中动态编译代码片段并且运行它,所以你在测试C#或VB.NET代码时不必再创建新的工程或解决方案了。

背景
通常我们需要测试一些代码片段(C#或VB.NET),在.NET环境中,我们用"CSC"或"VBC"命令;在VS.NET中,我们创建新的工程或解决方案,并且创建很多其他文件。这两种方法都是沉闷乏味的,特别是当我们测试一个很简单的程序时。jconwell创作了一种方法:"Dot Net Script",他使用XML文件(命名为"dnml")来包涵C#或VB代码。在这种方法里,dnml文件被解析并且代码在内存中被编译,这是个好方法!但是,它仍然有些小麻烦,因为它需要创建一个新文件。现在我们来做一个基于他的工作之上的工具。这个工具具有以下特点:
1、可以加载C#或VB代码文件,在内存中编译代码,然后通过一个静态方法("入口点")来运行这些代码。
2、若为VB.NET代码,并且它是一个"Form"类,工具将会添加一个"Main()"方法来运行这个窗体。
3、通过一个新的线程来运行代码。
4、有一个可视化的界面(如下面的截图)。

使用这个工具
像下面截图那样,点击按钮"Open..."可以打开一个C#或VB.NET文件;点击按钮"Paste"可以从剪贴板中粘贴代码到文本区;复选框"C#"用来标记代码是不是C#语言;那个文本框用来输入入口点(在C#中为静态方法,在VB.NET中为公共的Sub或Function);点击按钮"Run!"将会编译并运行代码。
public CompileEngine(string code, anguageType language, string entry)
2public void Run()
2private string PrepareRealSourceCode()
2// compile the source, and create assembly in memory
2// this method code is mainly from jconwell,
3// see http://www.codeproject.com/dotnet/DotNetScript.asp 4private Assembly CreateAssembly(string strRealSourceCode)
5// invoke the entry method
2// this method code is mainly from jconwell,
3// see http://www.codeproject.com/dotnet/DotNetScript.asp 4private void CallEntry(Assembly assembly, string entryPoint)
5private void btnRun_Click(object sender, System.EventArgs e)

private void RunTheProg()
{
string code = txtSource.Text.Trim();
LanguageType language = chkIsCSharp.Checked ?
LanguageType.CSharp : LanguageType.VB;
string entry = txtEntry.Text.Trim();

if( code == "" ) return;
if( entry == "" ) entry = "Main";

CompileEngine engine = new CompileEngine( code, language, entry );

engine.Run();
}
一些可以改进的地方
在PrepareRealSourceCode,用正则表达式来查找类名会更好一些。

感谢
感谢jconwell,VictorV,George Orwell,Eric Astor和其他朋友,他们在他们的主题里展示了很多优秀的作品,比如Dot Net Script,SnippetCompiler,Runtime Compilation。

关于dstang 2000
一个专业的开发人员。他使用Java,C#,VB,C和一些其他语言。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: