Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Reflection to get static method with its parameters

Tags:

c#

reflection

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.

like image 978
newbie_developer Avatar asked Jun 20 '12 10:06

newbie_developer


2 Answers

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 } );
like image 150
newbie_developer Avatar answered Oct 03 '22 01:10

newbie_developer


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
like image 40
Polity Avatar answered Oct 03 '22 01:10

Polity