简体   繁体   English

在Reflection中调用非静态方法

[英]Call Non-Static method in Reflection

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

You have two problems: 你有两个问题:

  1. Your BindingFlags are incorrect. 你的BindingFlags不正确。 It should be: 它应该是:

     MethodInfo method = t.GetMethod("Handle", BindingFlags.Instance | BindingFlags.Public); 

    Or you can remove the binding flags all together and use the Default Binding behavior, which will work in this case. 或者您可以一起删除绑定标记并使用默认绑定行为,这在这种情况下将起作用。

  2. Your Handle method as declared takes zero parameters, but you are invoking it with one parameter ( "Hello" ). 声明的Handle方法接受零参数,但是您使用一个参数( "Hello" )调用它。 Either add a string parameter to Handle: 向Handle添加字符串参数:

     public void Handle(string something) { Console.WriteLine("Order 1 "); } 

    Or don't pass in any parameters. 或者不传递任何参数。

You should use 你应该用

BindingFlags.Instance | BindingFlags.Public

in your call to GetMethod() . 在你对GetMethod()调用中。

BindingFlags.InvokeMethod (and other invocation flags) is not used by GetMethod() . GetMethod()不使用BindingFlags.InvokeMethod (和其他调用标志GetMethod() You can see what it's meant for in the documentation for Type.InvokeMember() . 您可以在Type.InvokeMember()的文档中看到它的含义。

您需要包含BindingFlags.Instance

除了已经提到的绑定标志之外,您似乎试图将参数传递给不带任何参数的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM