![](/img/trans.png)
[英]How can I change Assembly Version,Assembly File Version by compliling code using System.CodeDom.CodeCompileUnit
[英]How can I target a specific language version using CodeDOM?
使用C#代码提供程序和ICodeCompiler.CompileAssemblyFromSource
方法,我试图编译代码文件以生成可执行程序集。
我想编译的代码使用了可选参数和扩展方法等功能,这些功能仅在使用C#4语言时才可用。
话虽如此,我想编译的代码只需要(并且需要 )以.NET Framework 2.0版为目标。
使用前面的代码可以避免任何与语法有关的编译时错误,但是,生成的程序集将针对框架的4.0版本,这是不合需要的。
var compiler = new CSharpCodeProvider(
new Dictionary<string, string> { { "CompilerVersion", "v4.0" } } );
我怎样才能使代码提供程序针对语言版本4.0但生成一个只需要框架版本2.0的程序集?
您需要使用/ nostdlib选项指示要链接到另一个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.