fork(2) 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 Program
  9. {
  10. public static int Main(string[] args)
  11. {
  12. var targetClasses = new HashSet<string>(new[] { "Foo", "Foo2" });
  13. var targetFns = new HashSet<string>(new[] { "fn", "fn2", "fn3" });
  14. var j=0;
  15. foreach (var target in targetClasses)
  16. {
  17. Console.WriteLine("_class round {0}",j++);
  18. var i=0;
  19. foreach(var fn in targetFns)
  20. {
  21. Console.WriteLine("fn round {0}",i++);
  22. var method = (target.GetType().GetTypeInfo()) // (typeof(Foo).GetTypeInfo())
  23. .DeclaredMethods.Where(x => x.Name == fn).FirstOrDefault();
  24. if (method != null) //return 0;
  25. {
  26. var customAttributes = (MyCustomAttribute[])method
  27. .GetCustomAttributes(typeof(MyCustomAttribute), true);
  28. if (customAttributes.Length > 0)
  29. {
  30. var myAttribute = customAttributes[0];
  31. string value = myAttribute.SomeProperty;
  32. if (value == "bar")
  33. method.Invoke(null, null);
  34. // Foo.fn();;
  35. else
  36. Console.WriteLine("The attribute parameter is not as required");
  37. }
  38. }
  39. }
  40. }
  41. return 0;
  42. }
  43. }
  44. }
  45.  
  46. namespace attribute
  47. {
  48. [AttributeUsage(AttributeTargets.All)]
  49. public class MyCustomAttribute : Attribute
  50. {
  51. public string SomeProperty { get; set; }
  52. }
  53.  
  54.  
  55. public class Foo
  56. {
  57. [MyCustom(SomeProperty = "bar")]
  58. internal static void fn()
  59. {
  60. Console.WriteLine("a function in a class");
  61. }
  62.  
  63. [MyCustom(SomeProperty = "bar")]
  64. internal static void fn2()
  65. {
  66. Console.WriteLine("another function in the same class");
  67. }
  68. }
  69.  
  70. public class Foo2
  71. {
  72. [MyCustom(SomeProperty = "bar")]
  73. internal static void fn2()
  74. {
  75. Console.WriteLine("another function in a nother class");
  76. }
  77. }
  78. }
Success #stdin #stdout 0.01s 29936KB
stdin
Standard input is empty
stdout
_class round 0
fn round 0
fn round 1
fn round 2
_class round 1
fn round 0
fn round 1
fn round 2