gpt4 book ai didi

c# - 如何使用反射调用私有(private)方法?

转载 作者:IT王子 更新时间:2023-10-29 03:28:15 25 4
gpt4 key购买 nike

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

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

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

最佳答案

只需更改您的代码以使用重载的 version of GetMethod接受 BindingFlags:

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

这是 BindingFlags enumeration documentation .

关于c# - 如何使用反射调用私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/135443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com