打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用 c # 编译器编译代码
  • 2020/04/13

本文介绍如何使用 c # 编译器编译来自文本源的代码。

原始产品版本:  Visual Studio、.NET Framework
原始 KB 数:  304655

摘要

Microsoft .NET Framework 公开了允许以编程方式访问 c # 语言编译器的类。 如果要编写自己的代码编译实用程序,这可能很有用。 本文提供了示例代码,使您能够编译文本源中的代码。 通过应用程序,您只需生成可执行文件或生成可执行文件并运行它即可。 在编译过程中出现的任何错误都将显示在窗体上。

要求

  • Visual Studio

  • Visual c # 语言编译器

使用 c # 编译器编译代码

.NET Framework 提供 ICodeCompiler 编译器执行接口。 CSharpCodeProvider类实现此接口,并提供对 c # 代码生成器和代码编译器的实例的访问权限。 下面的代码示例创建一个实例 CSharpCodeProvider ,并使用它来获取对接口的引用 ICodeCompiler

C#
CSharpCodeProvider codeProvider = new CSharpCodeProvider();ICodeCompiler icc = codeProvider.CreateCompiler();

当您具有对接口的引用后 ICodeCompiler ,便可以使用它来编译源代码。 您将使用类将参数传递给编译器 CompilerParameters 。 如以下示例所示:

C#
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();parameters.GenerateExecutable = true;parameters.OutputAssembly = Output;CompilerResults results = icc.CompileAssemblyFromSource(parameters,SourceString);

上面的代码使用该 CompilerParameters 对象来通知编译器您要生成可执行文件(而不是 DLL),并且您希望将生成的程序集输出到磁盘。 对 CompileAssemblyFromSource 程序集进行编译的调用。 此方法采用 parameters 对象和源代码,这是一个字符串。 编译代码之后,可以检查是否存在任何编译错误。 您可以使用中的返回值 CompileAssemblyFromSource ,即 CompilerResults 对象。 此对象包含 errors 集合,该集合包含编译过程中发生的任何错误。

C#
if (results.Errors.Count > 0){    foreach(CompilerError CompErr in results.Errors)    {        textBox2.Text = textBox2.Text +            "Line number " + CompErr.Line +            ", Error Number: " + CompErr.ErrorNumber +            ", '" + CompErr.ErrorText + ";" +            Environment.NewLine + Environment.NewLine;    }}

还有其他一些编译选项,如从文件编译。 您还可以批量编译,这意味着您可以同时编译多个文件或源。

分步过程示例

  1. 创建新的 Visual c # .NET Windows 应用程序。 默认情况下会创建Form1

  2. Form1中添加一个 "按钮" 控件,然后将其 " Text " 属性更改为 "生成"。

  3. Form1中添加另一个按钮控件,然后将其Text属性更改为 "运行"。

  4. Form1中添加两个 TextBox 控件,将两个控件的多行属性设置为True,然后调整这些控件的大小,以便可以将多行文本粘贴到每一行。

  5. 在代码编辑器中,打开 " Form1.cs " 源文件。

  6. Form1 类中,粘贴以下按钮单击处理程序。

    C#
    private void button1_Click(object sender, System.EventArgs e){    CSharpCodeProvider codeProvider = new CSharpCodeProvider();    ICodeCompiler icc = codeProvider.CreateCompiler();    string Output = "Out.exe";    Button ButtonObject = (Button)sender;    textBox2.Text = "";    System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();    //Make sure we generate an EXE, not a DLL    parameters.GenerateExecutable = true;    parameters.OutputAssembly = Output;    CompilerResults results = icc.CompileAssemblyFromSource(parameters, textBox1.Text);    if (results.Errors.Count > 0)    {        textBox2.ForeColor = Color.Red;        foreach (CompilerError CompErr in results.Errors)        {            textBox2.Text = textBox2.Text +                        "Line number " + CompErr.Line +                        ", Error Number: " + CompErr.ErrorNumber +                        ", '" + CompErr.ErrorText + ";" +                        Environment.NewLine + Environment.NewLine;        }    }    else    {        //Successful Compile        textBox2.ForeColor = Color.Blue;        textBox2.Text = "Success!";        //If we clicked run then launch our EXE        if (ButtonObject.Text == "Run") Process.Start(Output);    }}

    在文件的开头,添加以下 using 语句:

    C#
    using System.CodeDom.Compiler;using System.Diagnostics;using Microsoft.CSharp;
  7. Form1.cs中,找到 Form1 构造函数。

  8. InitializeComponent在构造函数中调用后 Form1 ,添加以下代码以将按钮单击处理程序连接到添加到 Form1 的两个按钮。

    C#
    public Form1(){    InitializeComponent();    this.button1.Click += new System.EventHandler(this.button1_Click);    this.button2.Click += new System.EventHandler(this.button1_Click);}
  9. 运行项目。 加载Form1后,单击 "生成" 按钮。

    备注

    您会收到编译器错误。

  10. 接下来,将以下文本复制到 textbox 中,以替换任何现有文本:

    C#
    using System;namespace HelloWorld{    /// <summary>    /// Summary description for Class1.    /// </summary>    class HelloWorldClass    {        static void Main(string[] args)        {            Console.WriteLine("Hello World!");            Console.ReadLine();        }    }}
  11. 再次单击 "生成"。 编译应成功。

  12. 单击 "运行",它将编译代码并运行生成的可执行文件。 编译将创建一个名为Out.exe的可执行文件,该文件保存在您正在运行的应用程序所在的同一文件夹中。

    备注

    您可以修改 textbox 中的代码以查看不同的编译器错误。 例如,删除其中一个分号并重新生成代码。

  13. 最后,修改 textbox 中的代码,以将另一行文本输出到控制台窗口。 单击 "运行" 以查看输出。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
设计一个可以自已出题的PPT
Flash动画与Windows应用程序之间数据通信的研究与探讨
初中生也能学的编程不走弯路先用后学(Visual Basic环境)
乐创DIY C语言讲义​——2.4节(你好,世界)
c++ 与 matlab 混编
如何在PowerPoint里制作对话框?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服