如何获取方法的MethodBase对象?

Răz*_*nda 8 .net c# reflection methodbase

我正在尝试使用此帖子中找到的类,但它需要一个MethodBase才能运行.

我读了什么是获取MethodBase对象的最快方法?但我无法得到任何解决方案.

我需要做的是从函数中获取MethodBase对象.

例如,为Console类的静态函数WriteLine()获取MethodBase,或者为List <>的非静态函数Add()获取MethodBase.

谢谢你的帮助!

Ant*_*bry 14

方法1

您可以直接使用反射:

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
);
Run Code Online (Sandbox Code Playgroud)

在Console.Writeline()的情况下,该方法有许多重载.您需要使用GetMethod的其他参数来检索正确的参数.

如果该方法是通用的并且您不静态地知道类型参数,则需要检索open方法的MethodInfo,然后对其进行参数化:

// 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
Run Code Online (Sandbox Code Playgroud)

方法2

一些第三方库可以帮助您解决此问题.使用SixPack.Reflection,您可以执行以下操作:

MethodBase writeLine = MethodReference.Get(
    // Actual argument values of WriteLine are ignored.
    // They are needed only to resolve the overload
    () => Console.WriteLine("", null)
);
Run Code Online (Sandbox Code Playgroud)