Using Reflection to get static method with its par

2019-04-09 17:11发布

问题:

I'm using a public static class and static method with its parameters:

public static class WLR3Logon
{
   static void getLogon(int accountTypeID)
   {}
}

Now I am trying to fetch the method with its parameters into another class and using the following code:

MethodInfo inf = typeof(WLR3Logon).GetMethod("getLogon",
    BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);

int[] parameters = { accountTypeId };

foreach (int parameter in parameters)
{
    inf.Invoke("getLogon", parameters);
}

But its giving me error

"Object reference not set to an instance of an object."

Where I'm going wrong.

回答1:

This problem got solved by using the following approach:

using System.Reflection;    
string methodName = "getLogon";
Type type = typeof(WLR3Logon);
MethodInfo info = type.GetMethod(
    methodName, 
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

object value = info.Invoke(null, new object[] { accountTypeId } );


回答2:

There are many problems here

  • Your static method is Private yet you Select a method filtered on publicly visible access only. Either make your method public or ensure that the binding flags include private methods. Right now, no method will be found returning in inf being null which causes your null-ref exception.
  • The parameters is an array of ints where MethodInfo expects an array of objects. You need to ensure that you pass in an array of objects.
  • You loop over the parameters only to invoke the method multiple times with the whole parameter set. Remove the loop.
  • You call MethodInfo.Invoke with the name of the method as the first argument which is useless since this parameter is ment for instances when the method was an instance method. In your case, this argument will be ignored


回答3:

Your method is private as you have not explicitly declared an access modifier. You have two options to make your code work as intended:

  • Change your method to public.
  • Specify BindingFlags.NonPublic in the GetMethod call


回答4:

make your method public. It should work after that

 public static class WLR3Logon
 {
       public static void getLogon(int accountTypeID)
       {}
 }


标签: c# reflection