使用反射获取带有参数的静态方法 [英] Using Reflection to get static method with its parameters

查看:40
本文介绍了使用反射获取带有参数的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用公共静态类和静态方法及其参数:

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

但它给了我错误

未将对象引用设置为对象的实例."

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

我哪里出错了.

推荐答案

这个问题通过以下方法解决:

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

这篇关于使用反射获取带有参数的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆