查找属于InvocationExpressionSyntax的UsingDirectiveSyntax

时间:2016-09-12 13:15:48

标签: c# roslyn roslyn-code-analysis

在下面的代码中,“Console.WriteLine”调用需要使用“System”using指令才能工作。我已经有一个“使用System”的UsingDirectiveSyntax对象和一个“Console.Writeline”的InvocationExpressionSyntax对象。但是,如何使用Roslyn知道InvocationExpressionSyntax和UsingDirectiveSyntax对象是否相互属于?

using System;       
public class Program
{
   public static void Main()
   {
      Console.WriteLine("Hello World");
   }
}

1 个答案:

答案 0 :(得分:4)

InvocationExpressionSyntax的方法符号有一个成员ContainingNamespace,它应该等于从检索using指令的符号得到的命名空间符号。诀窍是使用Name成员作为查询语义模型的起点,因为整个UsingDirectiveSyntax不会给你一个符号。

Try this LINQPad query(或将其复制到控制台项目中),您将在查询的最后一行获得true;)

// create tree, and semantic model
var tree = CSharpSyntaxTree.ParseText(@"
    using System;
    public class Program
    {
       public static void Main()
       {
          Console.WriteLine(""Hello World"");
       }
   }");
var root = tree.GetRoot();

var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("SO-39451235", syntaxTrees: new[] { tree }, references: new[] { mscorlib });
var model = compilation.GetSemanticModel(tree);

// get the nodes refered to in the SO question

var usingSystemDirectiveNode = root.DescendantNodes().OfType<UsingDirectiveSyntax>().Single();
var consoleWriteLineInvocationNode = root.DescendantNodes().OfType<InvocationExpressionSyntax>().Single();

// retrieve symbols related to the syntax nodes

var writeLineMethodSymbol = (IMethodSymbol)model.GetSymbolInfo(consoleWriteLineInvocationNode).Symbol;
var namespaceOfWriteLineMethodSymbol = (INamespaceSymbol)writeLineMethodSymbol.ContainingNamespace;

var usingSystemNamespaceSymbol = model.GetSymbolInfo(usingSystemDirectiveNode.Name).Symbol;

// check the namespace symbols for equality, this will return true

namespaceOfWriteLineMethodSymbol.Equals(usingSystemNamespaceSymbol).Dump();