How to get a MethodBase object for a method?

北城余情 提交于 2019-12-04 03:17:27

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)
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!