How could I go about calling a method on a static class given the class name and the method name, please?
For example:
Given System.Environment
and GetFolderPath
, I'd like to use Reflection
to call Environment.GetFolderPath()
.
Because there is no instance variable, we access the members of a static class by using the class name itself. C# fields must be declared inside a class. However, if we declare a method or a field as static, we can call the method or access the field using the name of the class. No instance is required.
We currently do not allow two members declared in the same class to have the same name, even if one is static and the other is an instance member.
But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.
Just
Type.GetType(typeName).GetMethod(methodName).Invoke(null, arguments);
where typeName
is the name of the type as a string, methodName
is the name of the method as a string, and arguments
is an array of objects containing the arguments to call the method with.
First you need to get the Type (by iterating on the assembly using reflection)
see this link for details: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx
or use
Assembly.GetType
once you have the type in hand you can iterate over members using reflection or
MethodInfo method = typeof(MyClass).GetMethod("MyMethod");
then you can use MethodInfo.Invoke
and pass arguments to invoke the method when you want to invoke it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With