Guest User

Untitled

a guest
Aug 18th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. How to execute a private static method with optional parameters via reflection?
  2. public class Foo {
  3. private static void Bar(string key = "") {
  4. // do stuff
  5. }
  6. }
  7.  
  8. Foo.Bar()
  9.  
  10. Foo.Bar("")
  11.  
  12. var method = typeof(Foo).GetMethod("Bar", BindingFlags.Static | BindingFlags.NonPublic);
  13.  
  14. method.Invoke(obj: null, parameters: new object[] { "Test" });
  15.  
  16. foreach (ParameterInfo pi in method.GetParameters())
  17. {
  18. if (pi.IsOptional)
  19. {
  20. Console.WriteLine(pi.Name + ": " + pi.DefaultValue);
  21. }
  22. }
  23.  
  24. public class Foo
  25. {
  26. private static void Bar(string key = "undefined key", string value = "undefined value")
  27. {
  28. Console.WriteLine(string.Format("The key is '{0}'", key));
  29. Console.WriteLine(string.Format("The value is '{0}'", value));
  30. }
  31. }
  32.  
  33. MethodInfo mi = typeof(Foo).GetMethod("Bar", BindingFlags.NonPublic | BindingFlags.Static);
  34. ParameterInfo[] pis = mi.GetParameters();
  35.  
  36. object[] parameters = new object[pis.Length];
  37.  
  38. for (int i = 0; i < pis.Length; i++)
  39. {
  40. if (pis[i].IsOptional)
  41. {
  42. parameters[i] = pis[i].DefaultValue;
  43. }
  44. }
  45.  
  46. mi.Invoke(null, parameters);
  47.  
  48. private static void Bar(int number, string key = "undefined key", string value = "undefined")
  49.  
  50. parameters[0] = "23"
Add Comment
Please, Sign In to add comment