简体   繁体   中英

Using Reflection to get static method with its parameters

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.

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

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

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

make your method public . It should work after that

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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