开发者

invoke non static method by name

开发者 https://www.devze.com 2023-03-31 01:19 出处:网络
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 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,
    B开发者_运维问答indingFlags.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 error...

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

Solution: No "this" in Type.GetType("this")


try

 this.GetType().InvokeMember(
    methodName,
    BindingFlags.InvokeMethod,
    null,
    this,
    new object[] { sender, e }
  );

From MSDN

If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included


You can add BingingFlags.Instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消