首页 > 学院 > 开发设计 > 正文

【转载】#470 Define Your Own Custom Attribute

2019-11-17 03:16:36
字体:
来源:转载
供稿:网友

【转载】#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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表