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

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

问题描述

我的类中有一组私有方法,我需要根据输入值动态调用一个.调用代码和目标方法都在同一个实例中.代码如下所示:

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

在这种情况下,GetMethod() 不会返回私有方法.我需要向 GetMethod() 提供什么 BindingFlags 以便它可以定位私有方法?

解决方案

只需更改您的代码即可使用重载的 接受 BindingFlags 的 GetMethod 版本:

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

这是 BindingFlags 枚举文档.>

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

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?

解决方案

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

Here's the BindingFlags enumeration documentation.

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

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