如何使用Roslyn(Microsoft CodeAnalysis)获取范围内的所有可见局部变量名称

时间:2014-05-08 11:00:53

标签: c# roslyn

(请注意:这不是关于运行时反射/元信息)

我正在编写Roslyn CSharpSyntaxVisitor的具体实现

实施VisitIdentifierName

public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax name)
{
   var symbolInfo = _semanticModel.GetSymbolInfo(name);
   var fieldSymbol = symbolInfo.Symbol as IFieldSymbol;
   if (fieldSymbol != null)
   {
       // Here I would like to get all the local variable names what are visible
       // in the very same scope where this field IdentifierNameSyntax under visiting resides
       // We can suppose that _semanticNodel for the Document is available.
   }
}

1 个答案:

答案 0 :(得分:9)

调用SemanticModel.LookupSymbols(),然后过滤局部变量。

您可能还想过滤掉在该位置之后声明的本地人;见this code