Cas*_*roy 14 .net c# codedom csc
使用C#代码提供程序和 ICodeCompiler.CompileAssemblyFromSource方法,我试图编译代码文件,以生成可执行程序集.
我想编译的代码使用了可选参数和扩展方法等功能,这些功能仅在使用C#4语言时才可用.
话虽如此,我想编译的代码只需要(并且需要)以.NET Framework 2.0版为目标.
使用前面的代码可以避免任何与语法有关的编译时错误,但是,生成的程序集将以框架的4.0版为目标,这是不合需要的.
var compiler = new CSharpCodeProvider(
new Dictionary<string, string> { { "CompilerVersion", "v4.0" } } );
Run Code Online (Sandbox Code Playgroud)
我怎样才能使代码提供程序针对语言版本4.0但生成一个只需要框架版本2.0的程序集?
Sim*_*ier 11
您需要使用/ 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);
}
}");
}
Run Code Online (Sandbox Code Playgroud)
如果你运行它,它应该编译program.exe文件.如果你运行该文件,它应该显示如下:
Hello world from CLR version: 2.0.50727.7905
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1572 次 |
| 最近记录: |