【问题标题】:How to get a MethodBase object for a method?如何获取方法的 MethodBase 对象?
【发布时间】:2011-10-14 22:37:03
【问题描述】:

我正在尝试使用在 post 中找到的类,但它需要 MethodBase 才能运行。

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

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

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

感谢您的帮助!

【问题讨论】:

  • 这取决于您提前知道的内容 - 您是想在编译时了解确切的方法,还是从字符串中获取参考?
  • @Jon Skeet:在编译时知道方法和类名。我只需要 MethodBase,这样我就可以使用问题第一行链接中的类来找出该方法可以抛出的异常。这就是我想要达到的最终结果。

标签: c# .net reflection methodbase


【解决方案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
);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    相关资源
    最近更新 更多