如何使用CodeDOM定位特定语言版本?

时间:2013-11-16 13:24:40

标签: c# .net codedom csc

使用C#代码提供程序和ICodeCompiler.CompileAssemblyFromSource方法,我正在尝试编译代码文件以生成可执行程序集。

我想编译的代码使用了可选参数和扩展方法等功能,这些功能仅在使用C#4语言时才可用。

话虽如此,我想编译的代码只需要(并且需要)来定位.NET Framework的2.0版本。


使用前面的代码可以避免任何与语法有关的编译时错误,但是,生成的程序集将以框架的4.0版为目标,这是不合需要的。

var compiler = new CSharpCodeProvider(
        new Dictionary<string, string> { { "CompilerVersion", "v4.0" } } );

我如何才能使代码提供程序以语言 4.0版为目标,但生成的程序集只需要 framework 的2.0版本?

1 个答案:

答案 0 :(得分:11)

您需要使用/nostdlib option指示要链接到另一个mscorlib.dll的C#编译器(CSharpCodeProvider间接使用)。以下是应该执行此操作的示例:

static void Main(string[] args)
{
    // defines references
    List<string> references = new List<string>();

    // get a reference to the mscorlib you want
    var mscorlib_2_x86 = Path.Combine(
                         Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                         @"Microsoft.NET\Framework\v2.0.50727\mscorlib.dll");
    references.Add(mscorlib_2_x86);

    // ... add other references (System.dll, etc.)

    var provider = new CSharpCodeProvider(
                   new Dictionary<string, string> { { "CompilerVersion", "v4.0" } });
    var parameters = new CompilerParameters(references.ToArray(), "program.exe");
    parameters.GenerateExecutable = true;

    // instruct the compiler not to use the default mscorlib
    parameters.CompilerOptions = "/nostdlib";              

    var results = provider.CompileAssemblyFromSource(parameters,
        @"using System;

        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(""Hello world from CLR version: "" + Environment.Version);
            }
        }");
}

如果你运行它,它应该编译program.exe文件。如果您运行该文件,它应显示如下内容:

Hello world from CLR version: 2.0.50727.7905