如何使用反射调用私有方法? [英] How do I use reflection to invoke a private method?

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

问题描述

有一组在我的课私有方法,我需要的一个电话动态的基础上的输入值。二者调用code和目标方法是在相同的实例。在code是这样的:

There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });

在这种情况下, GetMethod的()将不会返回私有方法。什么的BindingFlags ,我需要提供给 GetMethod的(),以便它可以找到的私有方法?

In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?

推荐答案

只要改变你的code使用重载的 GetMethod的 接受的BindingFlags:

Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });

这里是的BindingFlags枚举文档

这篇关于如何使用反射调用私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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