如何使用 Roslyn 用字符串替换替换 C# 关键字? [英] How to replace C# keywords with string subsitutes using Roslyn?

查看:34
本文介绍了如何使用 Roslyn 用字符串替换替换 C# 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Roslyn 加载 C# 源代码并将其写入另一个文件,用替代品替换关键字.示例:

I'd like to use Roslyn to load C# sources and write it to another file, replacing keywords with substitutes. Sample:

for (int i=0; i<10; i++){}

翻译为

foobar (int i=0; i<10; i++){}

这种操作的语法是什么样的?

What the syntax for such operation could look like?

推荐答案

我不知道这会有多好,但是你可以用另一个 ForKeyword 替换每个 ForKeyword 标记 标记,但这次使用您的自定义文本.为此,您可以使用 CSharpSyntaxRewriter:

I don't know how well is this going to work, but you can replace each ForKeyword token with another ForKeyword token, but this time with your custom text. To do that, you can use CSharpSyntaxRewriter:

class KeywordRewriter : CSharpSyntaxRewriter
{
    public override SyntaxToken VisitToken(SyntaxToken token)
    {
        if (token.Kind() == SyntaxKind.ForKeyword)
        {
            return SyntaxFactory.Token(
                token.LeadingTrivia, SyntaxKind.ForKeyword, "foobar", "foobar",
                token.TrailingTrivia);
        }

        return token;
    }
}

使用此重写器,您可以编写如下代码:

Using this rewriter, you can write code like this:

string code = "for (int i=0; i<10; i++){}";

var statement = SyntaxFactory.ParseStatement(code);

var rewrittenStatement = new KeywordRewriter().Visit(statement);

Console.WriteLine(rewrittenStatement);

打印您想要的内容:

foobar (int i=0; i<10; i++){}

这篇关于如何使用 Roslyn 用字符串替换替换 C# 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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