首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为方法获取MethodBase对象?

如何为方法获取MethodBase对象?
EN

Stack Overflow用户
提问于 2011-07-28 16:53:40
回答 1查看 6.4K关注 0票数 8

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

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

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

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

谢谢你的帮忙!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-07-28 17:16:38

方法1

您可以直接使用反射:

代码语言:javascript
复制
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,然后将其参数化:

代码语言:javascript
复制
// 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

方法2

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

代码语言:javascript
复制
MethodBase writeLine = MethodReference.Get(
    // Actual argument values of WriteLine are ignored.
    // They are needed only to resolve the overload
    () => Console.WriteLine("", null)
);
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6856356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档