65.9K
CodeProject 正在变化。 阅读更多。
Home

C#编译器

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (32投票s)

2002 年 3 月 7 日

1分钟阅读

viewsIcon

463449

downloadIcon

7662

一个简单的 C# [VB.NET] 编译器,无需使用 csc.exe

Sample Image - compiler1.jpg

引言

CSCompiler 是一个用于编译单个 C# 源代码文件的简单应用程序。它使用 C# 编写。当然,我没有编写一个完整的 C# 编译器。而是使用了 .NET 平台提供的接口。

要拥有一个 C# 编译器,您需要做什么?

  1. 创建一个 CSharpCodeProvider (对于 Visual Basic,创建 VBCodeProvider) 的实例
  2. 获取 ICodeCompiler 接口
  3. 为编译器选项提供 CompilerParameters
  4. 使用 ICodeCompiler 接口的 CompileAssemblyFromSource 方法编译源代码
  5. 处理 CompilerResults
  6. 如果没有错误,则执行生成的应用程序

就是这样。

此方案使用代码作为字符串提供,但您也可以使用源文件。您也可以在内存中生成程序集,但生成二进制应用程序更适合查看编译器的“物理”结果。

这个简单的应用程序要求您输入应用程序的主类(这并不像它可能的那样棘手)。CSCompiler 应用程序的程序集引用对于大多数最简单的应用程序来说应该足够,但如果不是,您必须添加更多的程序集引用到 CompilerParamters 才能正常工作。

“编译并执行”按钮的代码如下所示:

private void button1_Click(object sender, System.EventArgs e)
{
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    // For Visual Basic Compiler try this :
    //Microsoft.VisualBasic.VBCodeProvider

    ICodeCompiler compiler = codeProvider.CreateCompiler();
    CompilerParameters parameters = new CompilerParameters();

    parameters.GenerateExecutable = true;
    if (appName.Text == "")    
    {
        System.Windows.Forms.MessageBox.Show(this, 
                               "Application name cannot be empty");
        return ;
    }

    parameters.OutputAssembly = appName.Text.ToString();

    if (mainClass.Text.ToString() == "")
    {
        System.Windows.Forms.MessageBox.Show(this, 
                               "Main Class Name cannot be empty");
        return ;
    }

    parameters.MainClass = mainClass.Text.ToString();
    parameters.IncludeDebugInformation = includeDebug.Checked;

    // Add available assemblies - this should be enough for the simplest
    // applications.
    foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) 
    {
        parameters.ReferencedAssemblies.Add(asm.Location);
    }

    String code = textBox1.Text.ToString();
    //System.Windows.Forms.MessageBox.Show(this, code);

    CompilerResults results = compiler.CompileAssemblyFromSource(parameters, 
                                                                 code);
            
    if (results.Errors.Count > 0) 
    {
        string errors = "Compilation failed:\n";
        foreach (CompilerError err in results.Errors) 
        {
            errors += err.ToString() + "\n";
        }
        System.Windows.Forms.MessageBox.Show(this, errors, 
                               "There were compilation errors");
    }
    else    
    {
        #region Executing generated executable
        // try to execute application
        try 
        {
            if (!System.IO.File.Exists(appName.Text.ToString())) 
            {
                MessageBox.Show(String.Format("Can't find {0}", appName), 
                                "Can't execute.", MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);
                return;
            }
            ProcessStartInfo pInfo = new ProcessStartInfo(appName.Text.ToString());
            Process.Start(pInfo);
        } 
        catch (Exception ex) 
        {
            MessageBox.Show(String.Format("Error while executing {0}", 
                    appName) + ex.ToString(), "Can't execute.", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        #endregion
                
    }
    
}

如果您想了解更多关于 CodeProvider 接口的信息,请查看 sourceforge 上的 NAnt 项目。

致谢

© . All rights reserved.