尝试使用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,但我的ReplaceToken与SyntaxFactory不起作用。 (它现在仅用于“++”而不是“ - ”):
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)) };
}
答案 0 :(得分:2)
尝试使用诊断的源范围而不是span参数。此外,span中第一个标记的父级不一定是您要查找的二进制表达式。您必须使用.AncestorsAndSelf()搜索父链,或使用FindNode()查找与span最匹配的节点。
此外,您正在检查令牌以查看它是否具有某种节点。通常,所有令牌类型都以令牌或关键字结束。您需要找到具有该SyntaxKind的节点。
答案 1 :(得分:0)
if (node.IsKind(SyntaxKind.SimpleAssignmentExpression))
{
var IncrementationClause = (BinaryExpressionSyntax)node;
var IncrementionClauseExpressionStatement = IncrementationClause.Parent;
string right = IncrementationClause.Right.ToString();
string left = IncrementationClause.Left.ToString();
var ExpressionNew = SyntaxFactory.ExpressionStatement(IncrementationClause);
if (right == left + " - 1")
{
var BonneIncrementation = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostDecrementExpression, IncrementationClause.Left);
ExpressionNew = SyntaxFactory.ExpressionStatement(BonneIncrementation).WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia(leading).WithTrailingTrivia(trailing);
}
else
{
var BonneIncrementation = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, IncrementationClause.Left);
ExpressionNew = SyntaxFactory.ExpressionStatement(BonneIncrementation).WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia(leading).WithTrailingTrivia(trailing);
}
var newRoot = root.ReplaceNode(IncrementionClauseExpressionStatement, ExpressionNew);
return new[] { CodeAction.Create("Convert in the good way of incrementing", document.WithSyntaxRoot(newRoot)) };
}