Using C# 6 features with CodeDomProvider (Roslyn)

前端 未结 5 1694
梦如初夏
梦如初夏 2020-12-01 08:56
CodeDomProvider objCodeCompiler = CodeDomProvider.CreateProvider( \"CSharp\" );

CompilerParameters objCompilerParameters = new CompilerParameters();

...

CompilerR         


        
5条回答
  •  不思量自难忘°
    2020-12-01 09:44

    Ran into this issue recently. For context, I was trying to run an MSTest project against a library project using System.CodeDom, but it always gave a compiler that implemented C# 5 whether or not I had Microsoft.Net.Compilers or Microsoft.CodeDom.Providers.DotNetCompilerPlatform packages referenced by the project under test.

    My fix for this was:

    • Use package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
    • Set package PrivateAssets to contentfiles;analyzers
    • Pass provider options with CompilerDirectoryPath set to the copied directory

    The default value for PrivateAssets is contentfiles;analyzers;build, so getting referencing projects to also copy the folder requires removing build from the setting.

    Example code:

    var compiler = CodeDomProvider.CreateProvider("cs", new Dictionary {
        { "CompilerDirectoryPath", Path.Combine(Environment.CurrentDirectory, "roslyn") }
    });
    

    Getting this to work with Microsoft.Net.Compilers would be slightly more tedious as no copy is made, but the end step of pointing CompilerDirectoryPath at the package's tools folder is the same.

提交回复
热议问题