繁体   English   中英

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

[英]Extract called method information using roslyn

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

 public void MyMethod()
 {
     dllObject.GetMethod();
 }

是否可以提取GetMethod的方法信息,例如其名称,类名称和程序集名称。

是的,您需要首先在语法树中搜索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;

几年前,我写了一篇关于Semantic Model的简短博客文章,可能对您有所帮助。

暂无
暂无

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

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