【发布时间】:2014-04-28 11:40:37
【问题描述】:
尝试使用 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)) };
}
【问题讨论】:
-
您应该分析语法树,而不是检查字符串表示。
ToString()可能不会返回您期望的结果。 -
我找到了方法,现在它进入了 CodeFix。但没有任何改变......我有一个 CodeAction,但没有执行任何操作。当我一步一步调试的时候,我可以看到newIncrementationClause和IncrementationClause完全一样。也许你可以帮助我:)
-
您正在替换刚刚创建的新节点,根据定义,该节点不在树中。你永远不应该使用
node.ToString();始终直接使用 Node API。
标签: c# roslyn diagnostics