【转载】#470 Define Your Own Custom Attribute

You can use predefined attributes to attach metadata to type members.

You can also define a custom attribute by creating a new class inheriting from System.Attribute. The class name must end in "Attribute". You typically define a conostructor that takes arguments that consist of the metadata that you want to attach to the type membere.

 1 /// <summary>
 2 /// Attach to a class method to indicate kg of methane that is
 3 /// output when calling the method.
 4 /// </summary>
 5 public class MethaneFootprintAttribute : Attribute
 6 {
 7     public double kgMethane;
 8  
 9     public MethaneFootprintAttribute(int kg)
10     {
11         kgMethane = kg;
12     }
13 }

You can use the new attribute to attach metadata to individual type members. You use the name of the new class, without the trailing "Attribute".

 1 [MethaneFootprint(45)]
 2 public void FeedCowInBarn()
 3 {
 4     Console.WriteLine("Cow eats slop in dim confines of barn");
 5 }
 6  
 7 [MethaneFootprint(29)]
 8 public void LetGrazeOutside()
 9 {
10     Console.WriteLine("Cow enjoys grazing and ends up healthier");
11 }

原文地址:#470 Define Your Own Custom Attribute

原文地址:https://www.cnblogs.com/yuthreestone/p/3614676.html