如何使用CodeDOM定位特定的语言版本? [英] How can I target a specific language version using CodeDOM?
问题描述
我使用C#代码提供程序和 ICodeCompiler.CompileAssemblyFromSource
方法,尝试编译代码文件以生成可执行程序集。
Using the C# code provider and the ICodeCompiler.CompileAssemblyFromSource
method, I am attempting to compile a code file in order to produce an executable assembly.
我要编译的代码利用了诸如可选参数和扩展方法之类的功能,这些功能仅在使用C#4语言时才可用。
The code that I would like to compile makes use of features such as optional parameters and extension methods that are only available when using the language C# 4.
话虽如此,我想编译的代码只需要(和需求)以.NET Framework 2.0版为目标。
Having said that, the code that I would like to compile only requires (and needs) to target version 2.0 of the .NET Framework.
使用后续代码可以避免任何与语法有关的编译时错误,但是,生成的程序集将以该框架的版本4.0是不可取的。
Using the proceeding code it is possible to avoid any compile-time errors pertaining to syntax however, the resulting assembly will target version 4.0 of the framework which is undesirable.
var compiler = new CSharpCodeProvider(
new Dictionary<string, string> { { "CompilerVersion", "v4.0" } } );
我该怎么做,以使代码提供者可以定位到语言版本4.0但是生成的装配只需要 framework 的2.0版?
How can I make is so that the code provider targets language version 4.0 but produces an assembly that only requires version 2.0 of the framework?
推荐答案
您需要使用以下命令指示要链接到另一个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
这篇关于如何使用CodeDOM定位特定的语言版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!