【问题标题】:Given a .NET method how can we know what methods, types, etc... does this method make use of?给定一个 .NET 方法,我们如何知道该方法使用了哪些方法、类型等……该方法使用了什么?
【发布时间】:2021-02-18 05:16:03
【问题描述】:

给定:

  1. .NET 程序集
  2. 属于程序集内某个类型的方法 (1)

如何找到方法 (2) 引用的 .NET 类型/方法?

我意识到反思在这里没有帮助。但是有什么作用呢?

【问题讨论】:

    标签: .net


    【解决方案1】:

    我能想到的最简单的方法是使用Mono.Cecil。您可以执行以下操作:

    using System;
    using System.Linq;
    using Mono.Cecil;
    
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                using var a = AssemblyDefinition.ReadAssembly(typeof(Program).Assembly.Location);
                var m = a.MainModule.Types.Single(c => c.Name == "Program").Methods.Single(c => c.Name == "Main");
                foreach(var inst in m.Body.Instructions)
                {
                    switch(inst.Operand)
                    {
                        case TypeReference tr:
                            System.Console.WriteLine(tr.FullName);
                            break;
    
                        case MethodReference mr:
                            System.Console.WriteLine(mr.ReturnType.FullName);
                            System.Console.WriteLine(mr.DeclaringType.FullName);
                            // ....
                            break;
    
                        // other member types...
                    }
                }
            }
        }
    }
    

    话虽如此,您也可以使用System.Reflection.Metadata,但是,IMO,后者要复杂得多。

    【讨论】:

    • System.Reflection.Metadata 可以做同样的事情吗?我知道我们可以使用常规的System.Reflection 库来获得表示方法主体的 IL 字节流,但这对我来说并不是很有用。我想考虑另一种选择的原因是,我在将源自 Mono.Cecil 的符号名称与来自 Roslyn 静态代码分析的符号名称匹配时遇到了麻烦。我在这里有一个相关的问题 - stackoverflow.com/questions/66499029/…
    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多