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()
.
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()
.
What you are doing here is reflecting on the type named
Environment
and using theGetPropery
andGetGetMethod
methods to get the get method of theEnvironment.CurrentDirectory
property like so;Calling the get method of a property returns it's value and is equivilent to;
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
once you have the type in hand you can iterate over members using reflection or
then you can use
MethodInfo.Invoke
and pass arguments to invoke the method when you want to invoke it.Here is a basic outline of what you would do:
Edit: This will work if you do not know the namespace of the static class. Otherwise use Daniel Brückner's solution as its much simpler.
Just
where
typeName
is the name of the type as a string,methodName
is the name of the method as a string, andarguments
is an array of objects containing the arguments to call the method with.