在反射中调用非静态方法
我似乎无法弄清楚如何从反射调用非静态方法(实例方法)。我做错了什么?真的很新/对反射一无所知(如果你没有注意到):
示例:
class Program
{
static void Main()
{
Type t = Type.GetType("Reflection.Order" + "1");
var instance = Activator.CreateInstance(t);
object[] paramsArray = new object[] { "Hello" };
MethodInfo method = t.GetMethod("Handle", BindingFlags.InvokeMethod | BindingFlags.Public);
method.Invoke(instance, paramsArray);
Console.Read();
}
}
public class Order1
{
public void Handle()
{
Console.WriteLine("Order 1 ");
}
}
I can't seem to figure out how to call a Non-Static method (Instance Method) From reflection. What am I doing wrong? Really new / ignorant with reflection (If you haven't noticed):
Example:
class Program
{
static void Main()
{
Type t = Type.GetType("Reflection.Order" + "1");
var instance = Activator.CreateInstance(t);
object[] paramsArray = new object[] { "Hello" };
MethodInfo method = t.GetMethod("Handle", BindingFlags.InvokeMethod | BindingFlags.Public);
method.Invoke(instance, paramsArray);
Console.Read();
}
}
public class Order1
{
public void Handle()
{
Console.WriteLine("Order 1 ");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您有两个问题:
您的 BindingFlags 不正确。应该是:
或者您可以一起删除绑定标志并使用默认绑定行为,这在这种情况下将起作用。
您声明的
Handle
方法采用零个参数,但您使用一个参数调用它 ("Hello"
)。要么向 Handle 添加一个字符串参数:或者不要传入任何参数。
You have two problems:
Your BindingFlags are incorrect. It should be:
Or you can remove the binding flags all together and use the Default Binding behavior, which will work in this case.
Your
Handle
method as declared takes zero parameters, but you are invoking it with one parameter ("Hello"
). Either add a string parameter to Handle:Or don't pass in any parameters.
您应该
在调用
GetMethod()
时使用。BindingFlags.InvokeMethod
(和其他调用标志)不被GetMethod()
使用。您可以在 Type.InvokeMember() 的文档中了解其含义。 。You should use
in your call to
GetMethod()
.BindingFlags.InvokeMethod
(and other invocation flags) is not used byGetMethod()
. You can see what it's meant for in the documentation forType.InvokeMember()
.您需要包含
BindingFlags.Instance
。You need to include
BindingFlags.Instance
.除了已经提到的绑定标志之外,您似乎还试图将参数传递给不接受任何参数的方法。
In addition to the binding flags already mentioned, you appear to be trying to pass an argument to a method that doesn't take any.