简体   繁体   中英

Call a static method of a static class using reflection

i trying to call a static method like this:

Assembly myAssembly = Assembly.LoadFrom(filePath);
Type Mytype = myAssembly.GetType("MyClass");
string returnedValue = Mytype.GetMethod("MyMethod").Invoke(null, null).ToString();
MessageBox.Show(returnedValue);

but i get this error: Object reference not set to an instance of an object.

internal static class MyClass
{
internal static string MyMethod(int param1)
{
return "HI"
}
}

Please help me to resolve this problem, regards.

First of all you need to pass correct BindingFlags so your method can be found:

var methodInfo = typeof(MyClass).GetMethod("MyMethod", 
                                           BindingFlags.Static |
                                           BindingFlags.NonPublic);

Then you need to pass correct parameters to the Invoke function:

methodInfo.Invoke(null, new object [] {1})

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