Advertisement
elena1234

Reflection - get methods and parameters

May 29th, 2021 (edited)
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. Type type = typeof(Car);
  2. // var method = type.GetMethod("MethodName");
  3.  
  4. var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
  5.  
  6. foreach(var method in methods)
  7. {
  8.    var parameters = method.GetParameters();
  9.  
  10.    foreach(var parameter in parameters)
  11.     {
  12.       Console.WriteLine($" - {paramter.ParameterType} {parameter.Name}"); // type and name
  13.     }
  14. }
  15.  
  16.  
  17. //
  18. var ferrari = new Ferrari();
  19. Type type = typeof(Ferrari);
  20. var method = type.GetMethod("Move"); // without BindingFlags if method is public or this will return null
  21. var returnValue = method.Invoke(ferrari, new object[] {23, 54}); // invoke method "Move" to object Ferrari with params 23, 54
  22.  
  23. //
  24.  public string CollectGettersAndSetters(string className)
  25.         {
  26.             Type type = typeof(Hacker);
  27.             var sb = new StringBuilder();
  28.             var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
  29.             foreach (var method in methods.Where(m=>m.Name.StartsWith("get"))) // get
  30.             {
  31.                 sb.AppendLine($"{method.Name} will return {method.ReturnType}"); // ReturnType
  32.             }
  33.  
  34.             foreach (var method in methods.Where(m => m.Name.StartsWith("set"))) // set
  35.             {
  36.                 sb.AppendLine($"{method.Name} will set field of {method.GetParameters().First().ParameterType}"); // ParameterType
  37.             }
  38.  
  39.             string result = sb.ToString().TrimEnd();
  40.             return result;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement