[英]invoke non static method by name
I've been trying to invoke a method by name but the problem is the method I invoke cannot be static and it needs to be of the current class. 我一直在尝试按名称调用方法,但问题是我调用的方法不能是静态的,它需要是当前类。
I've tried the way of doing it like this: 我试过这样做的方式:
public static void InvokeMenuMethod(string methodName, object sender, EventArgs e)
Type calledType = Type.GetType("MyNamespace.MyClass");
calledType.InvokeMember(
methodName,
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
null,
null,
new object[] { sender, e }
);
}
This obviously only works for static members so I tried something like this 这显然只适用于静态成员,所以我尝试过这样的事情
public static void InvokeMenuMethod(string methodName, object sender, EventArgs e)
Type calledType = Type.GetType("this");
calledType.InvokeMember(
methodName,
BindingFlags.InvokeMethod | BindingFlags.Public,
null,
null,
new object[] { sender, e }
);
}
But I get Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty). Parameter name: bindingFlags
但我得到Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty). Parameter name: bindingFlags
Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty). Parameter name: bindingFlags
error... Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty). Parameter name: bindingFlags
错误...
So how can I go about doing this? 那我怎么能这样做呢?
EDIT: 编辑:
So: 所以:
public void InvokeMenuMethod(string methodName, object sender, EventArgs e) {
Type.GetType("this").InvokeMember(
methodName,
BindingFlags.InvokeMethod,
null,
this,
new object[] { sender, e }
);
}
Gives a NullReferenceException
给出NullReferenceException
Solution: No "this" in Type.GetType("this")
解决方案: Type.GetType("this")
没有“this” Type.GetType("this")
try 尝试
this.GetType().InvokeMember(
methodName,
BindingFlags.InvokeMethod,
null,
this,
new object[] { sender, e }
);
If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included 如果自己指定了InvokeMethod,则会自动包含BindingFlags.Public,BindingFlags.Instance和BindingFlags.Static
您可以添加BingingFlags.Instance
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.