• Source
    1. using System;
    2. using System.Reflection;
    3.  
    4. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
    5. class HelpAttribute : Attribute
    6. {
    7. public string field = "field";
    8.  
    9. public string Help
    10. {
    11. get;
    12. set;
    13. }
    14.  
    15. public HelpAttribute()
    16. {
    17. Help = "no help";
    18. }
    19.  
    20. public HelpAttribute(string help)
    21. {
    22. this.Help = help;
    23. }
    24. }
    25.  
    26. [Help]
    27. class ClassWithCustomAttribute
    28. {
    29.  
    30. public ClassWithCustomAttribute()
    31. {
    32. ReadAttributes();
    33. // Method invoked only when debugging
    34. MethodDebug();
    35. }
    36.  
    37. [Obsolete("This method should not be used anymore!", true)]
    38. public void Method0()
    39. {
    40. // do smth
    41. }
    42.  
    43. [System.Diagnostics.Conditional("Debug")]
    44. public void MethodDebug()
    45. {
    46. Console.WriteLine("Method for debug!");
    47. }
    48.  
    49. protected void ReadAttributes()
    50. {
    51. // if AllowMultiple = false but inherited is true the base class Help is overridden by the Derive class Help attribute.
    52. Console.WriteLine("Assigned attributes of "+this+": ");
    53. foreach(HelpAttribute attr in this.GetType().GetCustomAttributes(true))
    54. {
    55. Console.WriteLine("\tHelp: \t" + attr.Help);
    56. Console.WriteLine("\tField: \t"+attr.field);
    57. }
    58. }
    59. }
    60.  
    61. [Help(field = "Some help field")]
    62. class DerivedClassWithCustomAttribute : ClassWithCustomAttribute
    63. {
    64. public DerivedClassWithCustomAttribute()
    65. {
    66. ReadAttributes();
    67. }
    68. }
    69.  
    70. public class Test
    71. {
    72. public static void Main()
    73. {
    74.  
    75. ClassWithCustomAttribute cca = new ClassWithCustomAttribute();
    76. // OUTPUT:
    77. // Assigned attributes:
    78. // Help: no help
    79. // Field: field
    80.  
    81. DerivedClassWithCustomAttribute dca = new DerivedClassWithCustomAttribute();
    82. // OUTPUT:
    83. // Assigned attributes of DerivedClassWithCustomAttribute:
    84. // Help: no help
    85. // Field: Some help field
    86.  
    87. // In case the Inherited option of AttributeUsage applied to HelpAttribute
    88. // we would get following output when invoke ctor of DerivedClassWithCustomAttribute:
    89. // OUTPUT:
    90. // Assigned attributes of DerivedClassWithCustomAttribute:
    91. // Help: no help
    92. // Field: Some help field
    93. // Help: no help
    94. // Field: field
    95.  
    96. }
    97. }