使用 Roslyn 和 .NET Core 生成 C# 代码 [英] Generate C# code with Roslyn and .NET Core

查看:40
本文介绍了使用 Roslyn 和 .NET Core 生成 C# 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to generate C# code using Roslyn with .NET Core. I've tried using the SyntaxFactory from the package Microsoft.CodeAnalysis.CSharp. The problem I'm currently stuck with is getting proper formatted code as text from it.

到目前为止我看到的所有样本都使用类似的东西

All the samples I've seen so far use something like

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

这里的问题是,他们都使用 Microsoft.CodeAnalysis.CSharp.Workspaces 包,目前该包与 .NET Core 不兼容.将 Roslyn 用作 .NET Core 的代码生成器,是否有任何替代路线或解决方法?

The problem here is, that they all use the package Microsoft.CodeAnalysis.CSharp.Workspaces which isn't compatible with .NET Core at the moment. Are there any alternative routes or workarounds for using Roslyn as a code generator with .NET Core?

推荐答案

Microsoft.CodeAnalysis.CSharp.Workspaces 1.3.2 包支持 netstandard1.3,所以它应该与 .Net Core 兼容.但它依赖于Microsoft.Composition 1.0.27,它只支持portable-net45+win8+wp8+wpa81.此框架名称与 .Net Core 兼容,但前提是您将其导入到 project.json 中.

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.

这意味着要完成这项工作,您的 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"
  }
}

这篇关于使用 Roslyn 和 .NET Core 生成 C# 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆