簡體   English   中英

CSharpCodeProvider似乎陷入了.NET 2.0,我如何獲得新功能?

[英]CSharpCodeProvider seems to be stuck at .NET 2.0, how do I get new features?

我有以下相當標准的代碼作為CSharpCodeProvider的包裝器。 這個類運行得很好,執行得很好,等等。但是,盡管我的應用程序是針對.NET 3.5構建的,並且在進行此編譯時引用了v3.5程序集,但我仍然無法訪問任何更好的C#3.5語法,如lambda或auto-properties。 有沒有辦法讓這個工作?

我的印象是這個類只是圍繞着csc.exe ,這個想法似乎被我的防火牆確認了(我的應用程序試圖訪問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;
}

編輯:

我現在引用了mscorlibSystem.CoreSystem.Text和我自己的程序集之一。

有一個編譯器標志,你可以傳遞給構造函數(在字典中):

Dictionary<string,string> options = new Dictionary<string,string>
{ 
    { "CompilerVersion", "v3.5" }
};

var compiler = new CSharpCodeProvider(options);

無論如何,這對我有用...

在引用的程序集中,嘗試添加對System.Core的引用。 應該這樣做。 那里有很多3.5功能。 如果不這樣做,請打開當前項目的構建屬性,並檢查可能需要加載的其他程序集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM