使用roslyn提取调用的方法信息

doo*_*man 1 c# roslyn

我需要使用 Roslyn 获取有关对 DLL 的方法调用的信息。例如,我有以下方法,其中 dllObject 是 DLL 文件的一部分。

\n\n
 public void MyMethod()\n {\n     dllObject.GetMethod();\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

是否可以提取 GetMethod 的方法信息,例如 it\xc2\xb4s 名称、类名称和程序集名称。

\n

Jos*_*rty 6

是的,您需要首先在语法树中搜索 an InvocationExpressionSyntax,然后使用SemanticModel检索它的完整符号,其中应包含有关其全名 ( .ToString())、类 ( .ContainingType) 和程序集 ( .ContainingAssembly) 的信息。

以下示例是自包含的,因此它不使用外部 DLL,但相同的方法应该适用于外部类型。

var tree = CSharpSyntaxTree.ParseText(@"
    public class MyClass {
            int Method1() { return 0; }
            void Method2()
            {
                int x = Method1();
            }
        }
    }");

var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);

//Looking at the first invocation
var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First();
var invokedSymbol = model.GetSymbolInfo(invocationSyntax).Symbol; //Same as MyClass.Method1

//Get name
var name = invokedSymbol.ToString();
//Get class
var parentClass = invokedSymbol.ContainingType;
//Get assembly 
var assembly = invokedSymbol.ContainingAssembly;
Run Code Online (Sandbox Code Playgroud)

Semantic Model几年前我写了一篇简短的博客文章,您可能会觉得有帮助。