在下面的代码中,“console.writeline”调用需要“system”使用指令才能工作。我已经有了“using system”的usingdirectivesyntax对象和“console.writeline”的invocationsyntax对象。但是,使用roslyn,我怎么知道调用表达式syntax和usingdirectivesyntax对象是属于彼此的呢?
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
}
}
最佳答案
InvocationExpressionSyntax
的方法符号有一个成员,该成员应等于从using指令的符号检索中获得的命名空间符号。这里的技巧是使用ContainingNamespace
成员作为查询语义模型的起点,因为整个Name
不会给您一个符号。
Try this LINQPad query(或将其复制到控制台项目中),您将在查询的最后一行得到UsingDirectiveSyntax
。
// 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();