尝试使用 Diagnostic 和 CodeFix 来制作转换它的代码:
variable = variable + 1;
otherVariable = otherVariable -1;
进入:
variable++;
otherVariable--;
已经完成诊断(有效):
var incrementing = node as BinaryExpressionSyntax;
if (incrementing != null)
{
string right = incrementing .Right.ToString();
string left = incrementing .Left.ToString();
if (right == left + " - 1" || right == left + " + 1")
{
addDiagnostic(Diagnostic.Create(Rule, incrementation.GetLocation(), "Use the shorter way"));
}
}
编辑: 我做了一些改变。 现在递增总是被识别。该程序进入 CodeFix,但我的带有 SyntaxFactory 的 ReplaceToken 不起作用。 (现在只针对“++”而不是“--”):
if (node.IsKind(SyntaxKind.SimpleAssignmentExpression)) //I use a node instead of a token
{
var IncrementationClause = (BinaryExpressionSyntax)node;
string left = IncrementationClause.Left.ToString();
left = left + "++";
string rigt = IncrementationClause.Right.ToString();
var newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.Left.ToString()), SyntaxFactory.Identifier(left));
newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.Right.ToString()), SyntaxFactory.Identifier(String.Empty));
newIncrementationClause = IncrementationClause.ReplaceToken(SyntaxFactory.Identifier(IncrementationClause.OperatorToken.ToString()), SyntaxFactory.Identifier(String.Empty));
var newRoot = root.ReplaceNode(IncrementationClause, newIncrementationClause);
return new[] { CodeAction.Create("Changer la mise en forme", document.WithSyntaxRoot(newRoot)) };
}
最佳答案
尝试使用诊断的源跨度而不是跨度参数。此外,跨度中第一个标记的父代不一定是您要查找的二进制表达式。您必须使用 .AncestorsAndSelf() 搜索父链或使用 FindNode() 找到与跨度最匹配的节点。
您还检查一个 token 以查看它是否具有节点类型。通常,所有 token 类型都以 token 或关键字结尾。您需要找到具有该 SyntaxKind 的节点。
关于c# - Roslyn C# 递增变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23340120/