找到属于 InvocationExpressionSyntax 的 UsingDirectiveSyntax

Find UsingDirectiveSyntax that belongs to InvocationExpressionSyntax

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

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

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();