简体   繁体   English

如何在Roslyn的类中查找未声明的变量?

[英]How to find variable declare is not use in the class in Roslyn?

In Roslyn how do I find out if a private member variable is not used in class? 在罗斯林(Roslyn)中,如何确定课堂上是否未使用私有成员变量?

I have task that to comment any unused private variables. 我的任务是注释所有未使用的私有变量。 For example: 例如:

class Test
{
   private int I;// if it's not use then i need to comment it out.
}

Create semantic model and pass it to the Rewriter class constructor in Main method. 创建语义模型,并将其传递给Main方法中的Rewriter类构造函数。

SemanticModel sm = Compilation.Create("StylecopImplementor")
    .AddReferences(MetadataReference.CreateAssemblyReference("mscorlib"))
    .AddSyntaxTrees(fileTree).GetSemanticModel(fileTree);

Rewriter syntaxwr = new Rewriter(sm);

I expose my semantic model to my Rewritter class. 我向Rewritter类公开了语义模型。

class Rewriter : SyntaxRewriter
{
    SemanticModel model { get; set; }
    IEnumerable<Diagnostic> diagonists;

    public Rewriter(SemanticModel pModel)
    {
        model = pModel;             
        diagonists = pModel.GetDiagnostics();
    }
}

Then I use below code in VisitVariableDeclaration. 然后,我在VisitVariableDeclaration中使用以下代码。

if (diagonists.Count() > 0)
{
    var diagitems = diagonists.Where(d => d.Info.MessageIdentifier.ToString().Equals("CS0168")).ToList();

    if (diagitems != null)
    {
        var ditem = diagitems.Where(d => d.Location.GetLineSpan(false).StartLinePosition.Line == node.GetLocation().GetLineSpan(false).StartLinePosition.Line).FirstOrDefault();

        if (ditem != null)
        {
            node = node.WithLeadingTrivia(Syntax.ParseTrailingTrivia("//"));                            
        }
    }
}

return base.VisitVariableDeclaration(node);

It will comment your variable declaration in your .cs file if it's not in use. 如果不使用它,它将在.cs文件中注释您的变量声明。

Compiler (as seen in VS.NET) will certainly issue a warning, you can get warnings from Roslyn too (found this ). 编译器(如被看见在VS.NET)肯定会发出警告,你可以从罗斯林得到警告过(发现这个 )。

For deeper code analysis I'd suggest using more advanced tool, for example Phoenix compiler. 为了进行更深入的代码分析,我建议您使用更高级的工具,例如Phoenix编译器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM