简体   繁体   English

我可以使用Roslyn完成此C#语法转换吗?

[英]Can I use Roslyn to accomplish this C# syntax transformation?

Two-part question here about adding C# syntax sugar using Roslyn: 关于使用Roslyn添加C#语法糖的两部分问题:

First, is it possible using Roslyn to add new syntax to C#, or does it always have to be a transformation from valid C# to other valid C#? 首先,是否可以使用Roslyn向C#中添加新语法,还是始终必须将其从有效C#转换为其他有效C#? For example, I'd like to do something like VB.NET's XML literals: 例如,我想做一些类似于VB.NET的XML文字:

XElement lvalue = <some><xml /></some>;

Is it possible to transform this at compile time to: 是否可以在编译时将其转换为:

XElement lvalue = new XElement("some", new XElement("xml")); // or whatever

Second, if that's possible, what does it look like to the user? 其次,如果可能的话,用户看起来像什么? Can I do this such that one writes the first expression, and never sees the transformation to the second expression (it happens transparently at compile-time)? 我是否可以这样做,以便人们编写第一个表达式,却从不看到对第二个表达式的转换(它在编译时透明地发生)? Or do Roslyn syntax transformations have to appear as sort of an IDE "refactoring suggestion"? 还是Roslyn语法转换必须作为一种IDE“重构建议”出现? I'm unclear on this from the Roslyn docs. 我不清楚Roslyn文档中的内容。

First, is it possible using Roslyn to add new syntax to C# 首先,是否可以使用Roslyn向C#添加新语法

Nope. 不。

or does it always have to be a transformation from valid C# to other valid C#? 还是总是必须将其从有效的C#转换为其他有效的C#?

Yep. 是的

Roslyn is a C#/VB analysis engine; Roslyn是C#/ VB分析引擎; those are the only languages it analyzes. 这些是它分析的唯一语言。 It is not for extending the C# or VB languages. 不是用于扩展C#或VB语言。

The C# compiler is open sourced under a fairly permissive license. C#编译器是在相当宽松的许可下开源的。 If you want to write your own version of it, you can certainly fork the repository and make the parser do whatever you like. 如果要编写自己的版本,则当然可以派生存储库,并使解析器执行您喜欢的任何事情。

If it has to look the the snippet you provided then no (without having to solve some much bigger problems), however you could go down a similar route that stackoverflow went with for localisation 如果必须查看您提供的代码片段,则无需(不必解决更大的问题),但是您可以沿着与stackoverflow相似的路径进行本地化

You could introduce something like _x("<some><xml /></some>") , you don't get much benefit in terms of syntax (cause you could have a runtime method that parses this), but you could have Roslyn take the work of replacing it with the exact code you want it to generate. 您可以引入类似_x("<some><xml /></some>") ,但是在语法方面并没有太大的好处(因为您可以使用运行时方法来对此进行解析),但是您可以Roslyn进行了将其替换为要生成的确切代码的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM