找到属于InvocationExpressionSyntax的usingdirectivessyntax
本文关键字:usingdirectivessyntax InvocationExpressionSyntax 属于 | 更新日期: 2023-09-27 18:06:35
在下面的代码中,WriteLine"调用需要"System" using指令才能工作。我已经有一个UsingDirectiveSyntax对象"使用系统"和一个InvocationExpressionSyntax对象"Console.Writeline"。但是我怎么知道,使用Roslyn, InvocationExpressionSyntax和usingdirectivessyntax对象属于彼此?
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
}
}
InvocationExpressionSyntax
的方法符号有一个成员ContainingNamespace
,该成员应该等于您从检索using指令的符号中获得的名称空间符号。这里的技巧是使用Name
成员作为查询语义模型的起点,因为整个UsingDirectiveSyntax
不会给您一个符号。
尝试这个LINQPad查询(或将其复制到控制台项目中),您将在查询的最后一行得到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();