c# - Roslyn C# 递增变化

标签 c# roslyn diagnostics

尝试使用 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/

相关文章:

c# - 如何保留 msbuild 输出的颜色?

c# - Roslyn 脚本 - 没有 "System"的脚本

.net - 如何使用 roslyn 检测 Visual Studio 2015 扩展中的符号重命名?

c# - Azure 诊断 - 加密 cscfg 中的连接字符串

c - Valgrind 如何能够访问已编译的 C 程序中内存分配的行号,我该怎么做?

C# 使用字典替换正则表达式匹配的模式

c# - 是 C# 还是 C#.NET?

c# - EntityFramework ToListAsync() 不起作用

c# - 如何在 Roslyn 中禁用不必要的 using 指令检查?

linux - 我如何获得(并学会有意义地解释)关于我的 Ubuntu 10.04 (Lucid) Linux 系统上 Wifi 子系统的非常低级的诊断?