Personal definition: Add object note information without invading objects.
Official definition: Associate predefined System information or user-defined custom information with a target element. The target element can be an assembly, class, constructor, delegate, enumeration, event, field, interface, method, portable Executable module, parameter, property, return value, structure, or other property (Attribute). The information provided is also known as metadata, which can be checked by the application at run time to control how the data is handled by the program, or by an external tool before it is run to check how the application processes or maintains itself.
The. Net Framework provides three predefined features:
- AttributeUsage
- Conditional
- Obsolete
Example: Reading attribute information added on an enumeration value
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacemyattribute{[Obsolete ("This is an expiration feature")] Public enumenumstate {[Remark ("I was opening")] //[Remark ("")]Open =1, [Remark ("I was off")] Close=2 }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Reflection;usingSystem.Text;usingSystem.Threading.Tasks;namespacemyattribute{//1. Characteristics of the scope of application 2. Whether the attribute is allowed to be used more than 3. Whether attributes are inherited by derived classes[AttributeUsage (attributetargets.all,allowmultiple =true, inherited =true)]//When invoked to perform conditional compilation, depending on the specified value (such as "DEBUG", "RELEASE" ...). )[Conditional ("DEBUG")] Public classRemarkattribute:attribute { Public stringremark; Public stringRemark {Get{returnremark;} } PublicRemarkattribute (stringremark) { This. Remark =remark; } } Public Static classRemarkextend { Public Static stringRemarkdescription ( Thisenumstate State) {Type type=typeof(enumstate); FieldInfo Info=type. GetField (state. ToString ()); Object[] remarkcustomattribute= info. GetCustomAttributes (typeof(Remarkattribute),false); if(Remarkcustomattribute! =NULL&& remarkcustomattribute.length>0) {Remarkattribute Remarkattribute= remarkcustomattribute[0] asRemarkattribute; returnRemarkattribute. Remark; } Else { returnState . ToString (); } } }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacemyattribute{classProgram {Static voidMain (string[] args) {Enumstate State=Enumstate.open; Console.WriteLine (state. Remarkdescription ()); Console.read (); } }}
At this point, learning about features is over, thank you for reading.
Features there are many advanced usage, Bo Master is only a small test sledgehammer, hope this article can help you, of course, if there is not perfect place, welcome to treatise.
Reference Msdn:https://msdn.microsoft.com/zh-cn/library/system.attribute (vs.80). aspx
C # features (Attribute)