为什么我不能通过字符串调用这个方法?
来自反射新手的问题。我在 Windows 窗体中有一个方法:
private void handleOrderCode()
{
//...do stuff
}
我尝试按以下方式调用该方法:
Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode");
if (mi != null) mi.Invoke(this, null);
我已确认“this”不为空。当此方法起作用时,字符串“handleOrderCode”已被硬编码的空间将被替换为字符串变量。然而,目前“mi”在最后一行的 if 语句中计算时始终为空。
那么我做错了什么?
Question from a Reflection newbie. I have a method in a Windows Form:
private void handleOrderCode()
{
//...do stuff
}
Which I am trying to call in the following manner:
Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode");
if (mi != null) mi.Invoke(this, null);
I have confirmed that "this" is not null. The space where the string "handleOrderCode" has been hardcoded is to be replaced with a string variable when this works. However, at present "mi" is always null when it evaluates in the if statement in the final line.
So what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要指定绑定标志:
因为没有任何标志的重载意味着:
即不会返回任何非公共(私有、受保护等)成员。
You need to specify binding flags:
Because overload without any flag means:
i.e. will not return any non-public (private, protected, etc) members.
仅 无参数重载
Type.GetMethod
寻找公共方法:您需要指定适当的
BindingFlags
< /a> 值改为另一个重载:请注意,您需要指定这里是“实例”或“静态”(或两者),而不仅仅是“非公开”。如果您还想查找公共方法,则也必须将其包含在内。
另一种选择是公开您的方法:)
(此外,我建议将其重命名为
HandleOrderCode
,以更传统、更惯用的 C#。)The parameterless overload of
Type.GetMethod
only looks for public methods:You need to specify an appropriate
BindingFlags
value to another overload instead:Note that you need to specify "instance" or "static" here (or both), not just "non-public". If you want to look for public methods as well, you have to include that too.
Another alternative is just to make your method public :)
(Additionally, I'd suggest renaming it to
HandleOrderCode
to be more conventional, idiomatic C#.)尝试:
try: