简体   繁体   English

使用Reflection获取带参数的静态方法

[英]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. 现在,没有找到方法返回inf为null,这会导致你的null-ref异常。
  • The parameters is an array of ints where MethodInfo expects an array of objects. 参数是一个int数组,其中MethodInfo需要一个对象数组。 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. 您使用方法的名称调用MethodInfo.Invoke作为第一个参数是无用的,因为当该方法是实例方法时,此参数是实例。 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 . 将您的方法更改为public
  • Specify BindingFlags.NonPublic in the GetMethod call GetMethod调用中指定BindingFlags.NonPublic

make your method public . 让你的方法public It should work after that 它应该在那之后工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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