简体   繁体   English

如何使用 Roslyn 获取方法调用/类声明的全名路径

[英]How to get full name path for method call/class declaration using Roslyn

How can I get the full qualified name of a method call with Roslyn?如何使用 Roslyn 获取方法调用的完整限定名称?

For example, Request.QueryString , comes from System.Web.UI , how am I able to detect that?例如, Request.QueryString来自System.Web.UI ,我怎么能检测到呢?

How about class declaration within same project but different namespaces?如何在同一个项目中但不同的命名空间中声明类? As well as function call from other classes of the same project.以及来自同一项目的其他类的函数调用。

Appreciate any form of help, thanks!感谢任何形式的帮助,谢谢!

You should create Compilation for all SyntaxTree for your all project files.您应该为所有项目文件的所有SyntaxTree创建 Compilation。 After it you can use symbol info for any node:之后,您可以对任何节点使用符号信息:

static string Code =
@"namespace TestNamespace
{
    public class Test
    {
        public int A { get; set; }
        public int B { get; set; }

        public Test(int a, int b)
        {
            A = a;
            B = b;
        }
    }
}";

static void Main(string[] args)
{
    var syntaxTree = CSharpSyntaxTree.ParseText(Code);
    var syntaxTrees = new SyntaxTree[] { syntaxTree }; // Add SyntaxTree array from project files.
    var compilation = CSharpCompilation.Create("tempAssembly", syntaxTrees);
    var semanticModel = compilation.GetSemanticModel(syntaxTree);
    var caretPosition = 46;
    var symbol = SymbolFinder.FindSymbolAtPositionAsync(semanticModel, caretPosition, new AdhocWorkspace()).Result;
    var fullName = symbol.ToString(); // fullName is "TestNamespace.Test"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM