如何获得一个方法MethodBase对象? [英] How to get a MethodBase object for a method?

查看:237
本文介绍了如何获得一个方法MethodBase对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想带班在此发现<一工作href="http://stackoverflow.com/questions/986180/how-can-i-determine-which-exceptions-can-be-thrown-by-a-given-method">post但它需要一个MethodBase运行

I am trying to work with the class found in this post but it needs a MethodBase to run.

我读<一href="http://stackoverflow.com/questions/6021558/what-is-the-fastest-way-to-get-a-methodbase-object">What是获得MethodBase对象的最快方法?但我无法得到任何解决方案正常工作。

I read What is the fastest way to get a MethodBase object? but i couldn't get any solution to work.

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

What i need to do is to get the MethodBase object from a function.

例如获得MethodBase的静态函数的WriteLine()类控制台或得到一个名单的MethodBase的非静态函数的Add()LT;>

For example getting the MethodBase for the static function WriteLine() of the class Console or getting the MethodBase for the non-static function Add() of a List<>.

感谢您的帮助!

推荐答案

方法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的附加参数,以获取正确的。

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.

如果该方法是通用的,你不知道类型参数静态,你需要检索的MethodInfo为开放式方法,然后参数化的:

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

方法2

某些第三方库可以帮助你与此有关。使用 SixPack.Reflection ,您可以执行以下操作:

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

这篇关于如何获得一个方法MethodBase对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆