Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- How to execute a private static method with optional parameters via reflection?
- public class Foo {
- private static void Bar(string key = "") {
- // do stuff
- }
- }
- Foo.Bar()
- Foo.Bar("")
- var method = typeof(Foo).GetMethod("Bar", BindingFlags.Static | BindingFlags.NonPublic);
- method.Invoke(obj: null, parameters: new object[] { "Test" });
- foreach (ParameterInfo pi in method.GetParameters())
- {
- if (pi.IsOptional)
- {
- Console.WriteLine(pi.Name + ": " + pi.DefaultValue);
- }
- }
- public class Foo
- {
- private static void Bar(string key = "undefined key", string value = "undefined value")
- {
- Console.WriteLine(string.Format("The key is '{0}'", key));
- Console.WriteLine(string.Format("The value is '{0}'", value));
- }
- }
- MethodInfo mi = typeof(Foo).GetMethod("Bar", BindingFlags.NonPublic | BindingFlags.Static);
- ParameterInfo[] pis = mi.GetParameters();
- object[] parameters = new object[pis.Length];
- for (int i = 0; i < pis.Length; i++)
- {
- if (pis[i].IsOptional)
- {
- parameters[i] = pis[i].DefaultValue;
- }
- }
- mi.Invoke(null, parameters);
- private static void Bar(int number, string key = "undefined key", string value = "undefined")
- parameters[0] = "23"
Add Comment
Please, Sign In to add comment