mark
mark

Reputation: 62722

Given a .NET method how can we know what methods, types, etc... does this method make use of?

Given:

  1. A .NET assembly
  2. A method belonging to a type inside the assembly (1)

How do I find which .NET types/methods the method (2) references?

I realize reflection does not help here. But what does?

Upvotes: 2

Views: 46

Answers (1)

Vagaus
Vagaus

Reputation: 4215

The easiest way I can think of is to use Mono.Cecil. You can do something like:

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...
                }
            }
        }
    }
}

That being said, you can also use System.Reflection.Metadata but, IMO, the latter is much more complex.

Upvotes: 1

Related Questions