如何在 C# 中创建格式和缩进代码
如何开始创建一个程序来将 C 及其派生代码格式化为 .net 样式格式化代码,以便我输入任何程序。该程序可以通过适当添加缩进和其他内容来识别和重新格式化。
How to start with creating a program to format C and their derived code into .net style formatted code so that if I input any program. This program can recognize and reformat by properly adding indentation and other things.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一项极其复杂的任务,因为编程语言具有复杂的语法。如果您不仅想格式化 C#,还想格式化 C 和 C++,那么情况会更加复杂 — 可能是不可能的,因为一种语言中的语法可能在另一种语言中无效(或含义不同)。
如果您只想为 C# 执行此操作,则需要一个 C# 解析器。有一些免费软件 C# 解析器可用:
有了解析树,您将必须遍历树并逐步以正确的格式输出它。某些 C# 解析器可能已经具有此功能。
关于语法歧义:考虑以下代码行:
在 C# 中,正确的格式是:
在 C 和 C++ 中,我相信正确的格式是:
This is an extremely complex task because programming languages have complex grammar. If you want to format not just C#, but C and C++ too, it’s even more complex — possibly impossible because there may be syntax in one language that is not valid (or means something different) in another.
If you want to do it just for C#, you need a C# parser. There are a few free-software C# parsers available:
Once you have the parse tree, you will have to walk the tree and progressively output it properly formatted. Some of the C# parsers may already have this functionality.
Regarding the grammar ambiguity: Consider the following line of code:
In C# the correct formatting would be:
In C and C++ I believe the correct formatting would be: