使用Roslyn和.NET Core生成C#代码

时间:2016-08-29 02:14:57

标签: c# roslyn .net-core

有没有办法使用带有.NET Core的Roslyn生成C#代码。我尝试过使用Microsoft.CodeAnalysis.CSharp软件包中的SyntaxFactory。我目前遇到的问题是将正确格式化的代码作为文本从中获取。

到目前为止,我见过的所有样本都使用类似

的内容
var ws = new CustomWorkspace();
ws.Options.WithChangedOption (CSharpFormattingOptions.IndentBraces, true);
var code = Formatter.Format (item, ws);

这里的问题是,他们都使用目前与.NET Core兼容的Microsoft.CodeAnalysis.CSharp.Workspaces软件包。是否有使用Roslyn作为.NET Core代码生成器的替代路由或解决方法?

1 个答案:

答案 0 :(得分:11)

The package Microsoft.CodeAnalysis.CSharp.Workspaces 1.3.2 supports netstandard1.3, so it should be compatible with .Net Core. But it depends on Microsoft.Composition 1.0.27, which only supports portable-net45+win8+wp8+wpa81. This framework moniker is compatible with .Net Core, but only if you import it in your project.json.

That means that to make this work, the relevant sections of your project.json should look like this:

"dependencies": {
    "Microsoft.CodeAnalysis.CSharp.Workspaces": "1.3.2"
},
"frameworks": {
  "netcoreapp1.0": {
    "dependencies": {
      "Microsoft.NETCore.App": {
        "type": "platform",
        "version": "1.0.0"
      }
    },
    "imports": "portable-net45+win8+wp8+wpa81"
  }
}