TWT*_*TWT 5 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");
}
}
Run Code Online (Sandbox Code Playgroud)
的方法符号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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |