通过MethodInfo调用方法 [英] Invoke method by MethodInfo

查看:183
本文介绍了通过MethodInfo调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用具有特定属性的方法. 因此,我循环遍历所有程序集和所有方法以查找具有我的属性的方法.工作正常,但是当我只有MethodInfo时如何调用某个方法.

I want to invoke methods with a certain attribute. So I'm cycling through all the assemblies and all methods to find the methods with my attribute. Works fine, but how do I invoke a certain method when I only got it's MethodInfo.

AppDomain app = AppDomain.CurrentDomain;
Assembly[] ass = app.GetAssemblies();
Type[] types;
foreach (Assembly a in ass)
{
    types = a.GetTypes();
    foreach (Type t in types)
    {
        MethodInfo[] methods = t.GetMethods();
        foreach (MethodInfo method in methods)
        {
            // Invoke a certain method
        }
    }
}

问题是我不知道包含该特定方法的类的实例.所以我不能正确地调用它,因为方法不是静态的. 如果可能,我还希望避免创建此类的新实例.

The problem is that I don't know the instance of the class that contains that certain method. So I can't invoke it properly because the methods are not static. I also want to avoid creating a new instance of this class if possible.

推荐答案

从问题定义(而不是编码)的角度来看,这使我成为一个问题.

This strikes me as an issue in terms of the problem definition rather than coding.

实例方法取决于调用它们的实例-在不关心实例方法被调用的情况下调用实例方法是没有意义的. (正如Martin所说,不管在哪个实例上被调用的实例方法几乎总是静态的.对此,我能想到的唯一的立即例外是虚拟方法,其中实例隐式指定了要使用的实现.)

Instance methods depend on which instance they're called on - it makes no sense to call an instance method without caring about what it's called on. (As Martin says, an instance method which doesn't care which instance it's being called on should almost always be static. The only immediate exception I can think of for this is virtual methods, where the instance implicitly specifies which implementation to use.)

弄清楚在您的上下文中真正的含义是什么,以便有一个带注释的实例方法.您为什么仍要尝试调用方法?更大的前景是什么?你有什么背景?我强烈怀疑您会需要上下文的一些概念-您可以 调用其实例方法的一组对象.

Work out what it really means in your context for there to be an annotated instance method. Why are you trying to invoke methods anyway? What's the bigger picture? What context do you have? I strongly suspect you'll want some notion of a context - a collection of objects which you can call the instance methods on.

这篇关于通过MethodInfo调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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