c# - 如何获取方法的 MethodBase 对象?

标签 c# .net reflection methodbase

我正在尝试使用此 post 中的类但它需要一个 MethodBase 才能运行。

我读了What is the fastest way to get a MethodBase object?但我找不到任何解决方案。

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

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

感谢您的帮助!

最佳答案

方法一

可以直接使用反射:

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
);

对于 Console.Writeline(),该方法有许多重载。您将需要使用 GetMethod 的附加参数来检索正确的参数。

如果该方法是泛型的并且您不知道静态类型参数,则需要检索打开方法的 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

方法二

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

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

关于c# - 如何获取方法的 MethodBase 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6856356/

相关文章:

C# 从 IL 中的静态方法调用并返回一个对象

java - 泛型 - 困惑

scala - C++ typeid 的 Scala 等价物是什么?

c# - 暂停和恢复线程事件

c# - 解析GML文件

c# - 不同命名空间中的相同类名 - 如何通过直接父命名空间访问类?

c# - 使用 Dapper 获取 UTC 日期时间

c# - C# 和 VB 中的 Overridable 和 Override

c# - "is"运算符在立即窗口中对盒装值的工作方式不同

c# - 本地获取 Chrome 和 Firefox 版本,C#