[英]How to find variable declare is not use in the class in Roslyn?
在羅斯林(Roslyn)中,如何確定課堂上是否未使用私有成員變量?
我的任務是注釋所有未使用的私有變量。 例如:
class Test
{
private int I;// if it's not use then i need to comment it out.
}
創建語義模型,並將其傳遞給Main方法中的Rewriter類構造函數。
SemanticModel sm = Compilation.Create("StylecopImplementor")
.AddReferences(MetadataReference.CreateAssemblyReference("mscorlib"))
.AddSyntaxTrees(fileTree).GetSemanticModel(fileTree);
Rewriter syntaxwr = new Rewriter(sm);
我向Rewritter類公開了語義模型。
class Rewriter : SyntaxRewriter
{
SemanticModel model { get; set; }
IEnumerable<Diagnostic> diagonists;
public Rewriter(SemanticModel pModel)
{
model = pModel;
diagonists = pModel.GetDiagnostics();
}
}
然后,我在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);
如果不使用它,它將在.cs文件中注釋您的變量聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.