Ariel
Ariel

Reputation: 41

Reflection and method usages

I have class A and class B in diferent assemblies, what I need to know is if there is a way to get the usages of the method A.foo() in class B's methods via reflection. I've read that maybe with IL?

Thanks for the help.

Upvotes: 3

Views: 224

Answers (3)

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

Have you considered using code analysis tools like Nitriq or NDepend? In NDepend's Code Query over LINQ it would be as easy as:

from t in Types 
where t.IsUsing ("ClassLibrary1.A.Foo()")
select new { t }

If you really need such information at runtime, there is NDepend.API available, you can use CQLinq there. But if I were you, I would double reconsider why I want to find such information at runtime...

Upvotes: 0

Saeed Neamati
Saeed Neamati

Reputation: 35822

You can read method bodies using GetMethodBody() method. Then you're on your own to find usages. I'm creating a sample ...

This sample might help:

   Assembly assembly = Assembly
       .GetAssembly(typeof(B));

   List<Type> types = assembly.GetTypes().ToList();

   Type controller = types
   .Where(t => t.Name == "a-class-name")
   .Single();

   List<MethodInfo> methods = controller
   .GetMethods().ToList();

   MethodInfo method = methods
   .Where(m => m.Name == "a-method-name")
   .First();

   MethodBody body = method
   .GetMethodBody();

   // Search body.LocalVariables

I actually wrote an article about this here.

Upvotes: 0

Servy
Servy

Reputation: 203817

No, you cannot do this with reflection. Reflection is based on the metadata of objects; the public APIs they expose. Their internal implementations are not accessible at all through reflection.

Upvotes: 2

Related Questions