代码之家  ›  专栏  ›  技术社区  ›  Matthew Scharley

CSharpCodeProvider似乎被困在.NET 2.0上,如何获取新功能?

c#
  •  12
  • Matthew Scharley  · 技术社区  · 16 年前

    我有以下相当标准的代码作为包装 CSharpCodeProvider . 这个类工作得很好,性能也很好,等等。但是,尽管我的应用程序是基于.NET 3.5构建的,并且在编译时引用v3.5程序集,但是我仍然无法访问任何非常好的C 3.5语法,如lambda或auto属性。有什么办法可以让这个工作吗?

    我的印象是这节课刚刚结束 csc.exe ,这一想法似乎得到了防火墙的确认(我的应用程序尝试访问 编译器 )也许我只是需要设置 options.CompilerOptions 为了什么?

    protected virtual void Compile()
    {
        Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
    
        CompilerParameters options = new CompilerParameters();
        options.GenerateExecutable = false;
        options.GenerateInMemory = true;
        options.IncludeDebugInformation = true;
    
        foreach (string s in this.ReferencedAssemblies)
        {
            options.ReferencedAssemblies.Add(s);
        }
    
        CompilerResults result;
        string source = this.CodeTemplate;
    
        // [snip] Do some manipulation to fill in the template with values.
    
        result = csProvider.CompileAssemblyFromSource(options, source);
    
        this.HasErrors = result.Errors.HasErrors;
        this.Errors = new CompilerError[result.Errors.Count];
        result.Errors.CopyTo(Errors, 0);
    
        if (HasErrors && ThrowOnErrors)
            throw new InvalidProgramException("The code currently stored in the " + this.GetType() + " cannot be compiled.");
        else if (HasErrors)
            return;
        this.CompiledAssembly = result.CompiledAssembly;
    }
    

    编辑:

    我提到过 mscorlib , System.Core , System.Text 和我自己的一个集会。

    2 回复  |  直到 14 年前
        1
  •  25
  •   Jon Skeet    16 年前

    有一个编译器标志可以传递给构造函数(在字典中):

    Dictionary<string,string> options = new Dictionary<string,string>
    { 
        { "CompilerVersion", "v3.5" }
    };
    
    var compiler = new CSharpCodeProvider(options);
    

    不管怎样,这就是我的工作……

        2
  •  0
  •   David Hedlund    16 年前

    在引用的程序集中,尝试添加对System.Core的引用。这应该可以做到。其中有很多3.5功能。如果不这样做,请打开当前项目的生成属性,并检查可能需要加载的其他程序集。