【转载】#470 Define Your Own Custom Attribute

王朝学院·作者佚名  2016-05-16
窄屏简体版  字體: 小  |  中  |  大  |  超大  

【转载】#470 Define Your Own Custom AttributeYou 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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航