How to get a MethodBase object for a method?
Asked Answered
Q

1

9

I am trying to work with the class found in this post but it needs a MethodBase to run.

I read What is the fastest way to get a MethodBase object? but i couldn't get any solution to work.

What i need to do is to get the MethodBase object from a function.

For example getting the MethodBase for the static function WriteLine() of the class Console or getting the MethodBase for the non-static function Add() of a List<>.

Thanks for your help!

Questor answered 28/7, 2011 at 8:53 Comment(2)
It depends what you know ahead of time - are you trying to get a reference knowing the exact method at compile time, or is this from strings?Selfsatisfied
@Jon Skeet: Knowing the method and class name at compile time. I just need the MethodBase so i can use the class in the link on 1st row of my question to find out what exceptions that method can throw. That is the final result i want to achieve.Lallage
D
15

Method 1

You can use reflection directly:

MethodBase writeLine = typeof(Console).GetMethod(
    "WriteLine", // Name of the method
    BindingFlags.Static | BindingFlags.Public, // We want a public static method
    null,
    new[] { typeof(string), typeof(object[]) }, // WriteLine(string, object[]),
    null
);

In the case of Console.Writeline(), there are many overloads for that method. You will need to use the additional parameters of GetMethod to retrieve the correct one.

If the method is generic and you do not know the type argument statically, you need to retrieve the MethodInfo for the open method and then parametrize it:

// No need for the other parameters of GetMethod because there
// is only one Add method on IList<T>
MethodBase listAddGeneric = typeof(IList<>).GetMethod("Add");

// listAddGeneric cannot be invoked because we did not specify T
// Let's do that now:
MethodBase listAddInt = listAddGeneric.MakeGenericMethod(typeof(int));
// Now we have a reference to IList<int>.Add

Method 2

Some third-party libraries can help you with this. Using SixPack.Reflection, you can do the following:

MethodBase writeLine = MethodReference.Get(
    // Actual argument values of WriteLine are ignored.
    // They are needed only to resolve the overload
    () => Console.WriteLine("", null)
);
Durra answered 28/7, 2011 at 9:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.