[英]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 method is private as you have not explicitly declared an access modifier. 您的方法是私有的,因为您没有显式声明访问修饰符。 You have two options to make your code work as intended: 您有两种方法可以使代码按预期工作:
public
. 将您的方法更改为public
。 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.