且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-25 21:19:51

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

You need to instruct the C# compiler (that CSharpCodeProvider uses indirectly) that you want to link to another mscorlib.dll, using the /nostdlib option. Here is a sample that should do it:

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文件。如果运行该文件,它将显示以下内容:

If you run this, it should compile a program.exe file. If you run that file, it should display something like this:

Hello world from CLR version: 2.0.50727.7905