保持与未知的签名方法字典来用反射调用 [英] Keep a dictionary of methods with unknown signature to be invoked with reflection

查看:105
本文介绍了保持与未知的签名方法字典来用反射调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个使用字符串作为键和一些表示方法的字典, 所有这些都可能有不同的签名,以,作为值。从这个事情,我应该能够访问的MethodInfo 和对象的实例如果方法不是静态的,这样以后我可以通过名字找到它并调用它使用反射。

I want to have a dictionary which uses strings as keys and something that represents methods, all of which may have different signatures, as values. From this something, I should be able to access a MethodInfo and an instance of an object if the method is not static, such that later on I can find it by name and invoke it using reflection.

我觉得代表会做,但我不能找到一种方法来施放一个静态或实例法成代表。我还可以创建自己的类或结构保存对象和的MethodInfo ,但即便如此,班里的用户必须获得的MethodInfo 关闭任何他想做的方法添加到我的字典,将需要添加一个引用反射随处可见(而不是也许只是路过方法本身的或者像(代表)myMethod的)。有没有办法做到这一点?

I thought Delegate would do, but I cannot find a way to cast a static or instance method into a Delegate. I could also create my own class or structure that holds an object and a MethodInfo, but if so, my class' users would have to get a MethodInfo off of whatever method he wants to add to my dictionary and would need to add a reference to Reflection everywhere (instead of perhaps just passing the method itself or something like (Delegate)myMethod). Is there a way to do this?

推荐答案

如果你不介意每次都指定一个委托类型,你添加到字典,那么你可以使用代表

If you don't mind specifying a delegate type each time you add to the dictionary, then you can use Delegate:

void A() {}
string B(string arg) { return arg; }

void Test()
{
    var dict = new Dictionary<string, Delegate>();

    dict.Add("A", new Action(A));
    dict.Add("B", new Func<string, string>(B));
}

这篇关于保持与未知的签名方法字典来用反射调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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