具有診斷和CodeFix試圖讓誰變換代碼:羅斯林C#遞增變化
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)) };
}
你應該分析語法樹,不檢查字符串表示。 'ToString()'可能不會返回你所期望的。 – SLaks
我已經找到了方法,現在它進入CodeFix。但沒有任何改變......我有一個CodeAction,但沒有任何行動。當我逐步調試時,我可以看到newIncrementationClause與IncrementationClause完全相同。也許你可以幫我:) – Maloz
你正在替換你剛創建的新節點,它根據定義不在樹中。你不應該使用'node.ToString()';總是直接使用Node API。 – SLaks