问题
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++){}
translated to
foobar (int i=0; i<10; i++){}
What the syntax for such operation could look like?
回答1:
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);
Which prints what you wanted:
foobar (int i=0; i<10; i++){}
回答2:
You'll want to look at creating a SyntaxWalker
that walks over the entire tree and copies it to your output file, except for elements that are keyword tokens.
回答3:
Just for the record - following code also worked but accepted answer is much more elegant.
foreach (var t in tree.GetCompilationUnitRoot().DescendantTokens())
{
if (t.HasLeadingTrivia)
{
file.Write(t.LeadingTrivia);
}
file.Write(t.IsKind(SyntaxKind.ForKeyword)? "foobar" : t.ToString());
if (t.HasTrailingTrivia)
{
file.Write(t.TrailingTrivia);
}
}
来源:https://stackoverflow.com/questions/26585869/how-to-replace-c-sharp-keywords-with-string-subsitutes-using-roslyn