How to dynamically call a method with optional arguments?
I need your help.
Can the following be done with C #?
I have a method
void SomeMethod(int p1 = 0, bool p2 = true, string p3 = "")
{
// some code
}
And I need to call this method with an unknown number of arguments at compile time. I mean, on startup, the application has to load the argument information from the xml (for example) and call a method with those arguments. The Xml file can contain 0 to 3 arguments.
How to call SomeMethod method with unknown number of arguments loaded from xml?
thank
+3
source to share
2 answers
You can do this using reflection:
- Receive
MethodInfo
passing of all three types of parameters. - Get runtime parameter values
- Get parameter metadata
ParameterInfo\[\]
fromMethodInfo
by callingGetParameters()
- For each missing parameter, check
HasDefaultValue
and takeDefaultValue
if it is - Add an array of default values to the array of passed values. You will have an array of three objects
- Pass the resulting array to the method you got with reflection.
+6
source to share