fork download
  1. using System;
  2. using System.Collections.Generic; // for HashSet
  3. using System.Linq; // for using Where
  4. using System.Reflection;
  5.  
  6. namespace attribute
  7. {
  8. public class Test
  9. {
  10. public static void Main()
  11. {
  12. var targetClasses = new HashSet<string>(new[] { "Foo", "Foo2" });
  13. var targetFns = new HashSet<string>(new[] { "fn", "fn2", "fn3" });
  14.  
  15. foreach (var target in targetClasses){
  16. foreach(var fn in targetFns){
  17. var method = (target.GetType().GetTypeInfo()) // (typeof(Foo).GetTypeInfo())
  18. .DeclaredMethods.Where(x => x.Name == fn).FirstOrDefault();
  19. if (method != null) //return 0;
  20. {
  21. var customAttributes = (MyCustomAttribute[])method
  22. .GetCustomAttributes(typeof(MyCustomAttribute), true);
  23. if (customAttributes.Length > 0)
  24. {
  25. var myAttribute = customAttributes[0];
  26. bool value = myAttribute.condition;
  27. Console.WriteLine(value);
  28. if (value == true)
  29. method.Invoke(null, null);
  30. else
  31. Console.WriteLine("The attribute parameter is not as required");
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }
  38. }
  39.  
  40.  
  41. namespace attribute
  42. {
  43. [AttributeUsage(AttributeTargets.All)]
  44. public class MyCustomAttribute : Attribute
  45. {
  46. public bool condition { get; set; }
  47. }
  48.  
  49.  
  50. public class Foo
  51. {
  52. [MyCustom(condition= true ? ("bar" == "bar") : false)]
  53. internal static void fn()
  54. {
  55. Console.WriteLine("a function in a class");
  56. }
  57.  
  58. [MyCustom(condition= true ? (1 == 2) : false)]
  59. internal static void fn2()
  60. {
  61. Console.WriteLine("another function in the same class");
  62. }
  63. }
  64.  
  65. public class Foo2
  66. {
  67. [MyCustom(condition= true ? (1 == 1) : false)]
  68. internal static void fn2()
  69. {
  70. Console.WriteLine("another function in a nother class");
  71. }
  72. }
  73. }
Success #stdin #stdout 0s 29288KB
stdin
Standard input is empty
stdout
Standard output is empty