invoke non static method in c#

2.7k Views Asked by At

I want to invoke a class "***" is the solution that works for me but I want to invoke THIS IS THE SOLUTION THAT GIVES ME THE ERROR :

Type t = Type.GetType(svClass);
MethodInfo method = t.GetMethod("execute", BindingFlags.instance| BindingFlags.Public);

Ret = (string)method.Invoke(null, new object[] { context.Request});
    public string execute(HttpRequest req)

so that I tried to MethodInfo method = t.GetMethod("execute", BindingFlags.instance | BindingFlags.Public);

but it gives me the error "non-static method requires a target"

*** THIS IS THE WORKING SOLUTION FOR STATIC METHOD

Type t = Type.GetType(svClass);
MethodInfo method = t.GetMethod("execute", BindingFlags.static| BindingFlags.Public);

Ret = (string)method.Invoke(null, new object[] { context.Request});

to invoke

public class XXXXX
    {
        public static string execute(HttpRequest req){}
    }
1

There are 1 best solutions below

1
On

The secret is to change your binding flags to get a MethodInfo that matches the signature of the method you wish to call.

Eg:

 public static string execute(HttpRequest req){}

Will be accessed via

MethodInfo method = t.GetMethod("execute", BindingFlags.static| BindingFlags.Public);

However, to access

public string execute(HttpRequest req){}

you need to do

var classObj = new Class();
MethodInfo method = classObj.GetType().GetMethod("execute", BindingFlags.Instance| BindingFlags.Public);

Instance means that the method is a member of a class object, and not of the class type. (Instance vs Static)

var parameterArray = new object[]{ YourHttpRequestHere};
var result = method.Invoke(classObj,parameterArray);

So remember, if the method belongs to an instance, then you need to grab the method from that instance type, and then you need to invoke it with a reference to the instance variable (classObj) above.