metadata, which is the class encapsulated in C #, cannot be modified. The attributes of a class member are referred to as annotations in the metadata.
1. What is a feature
(1) distinction between attributes and properties
Property : A property is an object-oriented idea that encapsulates a data field within a class, Get,set method.
feature (Attribute): official explanation: An attribute is an additional declarative information given to a specified declaration. A description declaration that allows similar keywords. It labels the elements in the program, such as types, fields, methods, properties, and so on. From the. NET perspective, attributes are classes that inherit from the System.Attribute class and are used to describe classes, properties, methods, events, and so on, primarily in reflection. But from an object-oriented level, attribute is actually a type-level, not an object-level.
The elements of the attributes and. net files are stored together and can be used to describe your code to the runtime, or to affect the behavior of the program as it runs.
2, the application of characteristics
(1). NET features are used to handle a variety of problems, such as serialization, the security features of the program, preventing the immediate compiler from optimizing the program code, and so the code is easy to debug.
The colonization feature is essentially an element of a class that adds additional information and runs it through reflection to get that additional information (often used when working with data entity objects)
(2) Application of Attribute as a compiler directive
Conditional: The role of conditional compilation, which allows the compiler to compile its code only if the condition is met. Generally used when debugging a program
DllImport: A function used to mark fee. NET, which indicates that the method is defined in an external DLL.
Obsolete: This property is used to mark that the current method has been deprecated and is no longer used
Note: attribute is a class, so DllImport is also a class, and the attribute class is instantiated at compile time , rather than instantiated at run time as usual.
CLSCompliant: Ensure that the entire assembly code complies with the CLS, otherwise the compilation will error.
3. Custom Features
Use AttributeUsage to control how the newly defined features are applied
[AttributeUsageAttribute(AttributeTargets.All can be applied to any element
, Allowmultiple=true, allows the application to be repeated multiple times, and our fixed-value feature can be duplicated several times before the same program entity.
, Inherited=false, do not inherit to derived
)]
The attribute is also a class that must inherit from the System.Attribute class, and the naming convention is class name +attribute. Whether directly or indirectly, inheritance becomes an attribute class, and the declaration of an attribute class defines a new attribute that can be placed on top of the declaration.
public class MyselfAttribute:System.Attribute
4. Custom Features Case
The following is an effect of the Save () method similar to the session in Hibernate, which automatically persists object information to the database to illustrate the use of custom attributes.
(1) Establishment of Dept table
Create TableDept (DeptNoint Identity(1,1)Primary Key, Dnamenvarchar(Ten) not NULL, Descriptionnvarchar( -) ) Go --how to ask Hovertree.com
(2) Custom attribute classes
/************** custom Attribute class *****************/ /// <summary> ///role: Used to describe what the table name is///AttributeUsage: Describes what the target element of the attribute is///AttributeTargets.Class: Represents the target element as Class/// </summary> [AttributeUsage (AttributeTargets.Class)] Public classtableattribute:attribute{/// <summary> ///Table name/// </summary> Public stringTableName {Get;Set; } #regionMethod of construction, optional PublicTableattribute () {} PublicTableattribute (stringtableName) { This. TableName =TableName; } #endregion } /************** custom Attribute class *****************/ /// <summary> ///action: Indicates whether the column is an auto-grow column/// </summary> [AttributeUsage (attributetargets.property)]classIdentityattribute:attribute {/// <summary> ///true: Yes; false: No/// </summary> Public BOOLisidentity {Get;Set; } } /**************** entity class ***************/ /// <summary> ///intentionally defining the class name as inconsistent with the table name///Use the table attribute to describe what the table name of the entity class is/// </summary>[Table (TableName ="Dept")] Public classDepartment {/// <summary> ///department number, marked as automatic growth with attributes/// </summary>[Identity (isidentity=true)] Public intDeptNo {Get;Set; } /// <summary> ///Department Name/// </summary> Public stringdname {Get;Set; } /// <summary> ///Department Description/// </summary> Public stringDescription {Get;Set; } PublicDepartment (stringNamestringdesc) {Dname=name; Description=desc; } } /**************** Execution Persistence operation class ***************/ /// <summary> ///To perform a persisted operation class/// </summary> Public classAdomanager {/// <summary> ///adds an object's property value as the value of the corresponding column in the table/// </summary> /// <param name= "obj" >the object to add</param> Public intSave (Object obj) {//1. Obtain the class name: Represents the table name and uses the reflection stringTableName =obj. GetType (). Name; //if the class has a Tableattribute attribute, the class name that takes the attribute descriptionTableattribute attr = Attribute.GetCustomAttribute (obj. GetType (),typeof(Tableattribute)) asTableattribute; if(attr! =NULL) {//the Description class adds the table attributeTableName = attr. TableName;//Get table name } //SQL statement Template: INSERT into Dept (deptno,dname,description) VALUES (' 2 ', ' ', '); StringBuilder sql =NewStringBuilder ("Insert into"); Sql. Append (TableName); Sql. Append (" ("); //property name of the looping object: Get column name foreach(PropertyInfo Iteminchobj. GetType (). GetProperties ()) {//whether there is an auto-growth featureIdentityattribute att = attribute.getcustomattribute (item,typeof(Identityattribute)) asIdentityattribute; if(Att = =NULL|| !att. isidentity) {//No, the column is addedSQL. Append (item. Name); Sql. Append (","); } } //remove the last comma 'Sql. Remove (SQL. Length-1,1); Sql. Append (") VALUES ("); //loop out the property value of an object: Assign a value to a column foreach(PropertyInfo Iteminchobj. GetType (). GetProperties ()) {//whether there is an auto-growth featureIdentityattribute att = attribute.getcustomattribute (item,typeof(Identityattribute)) asIdentityattribute; if(Att = =NULL) {//No, append the value of the column//GetValue (): What object obj represents, null for no argumentsSql. Append ("'"+ Item. GetValue (obj,NULL) +"'"); Sql. Append (","); } } //remove the last comma 'Sql. Remove (SQL. Length-1,1); Sql. Append (")"); //View the full SQL statementConsole.WriteLine (SQL. ToString ()); //Execute SQL statementSqlConnection conn =NewSqlConnection ("server=.; database=test;integrated security=true"); SqlCommand Comm=NewSqlCommand (SQL. ToString (), conn); Conn. Open (); intR =Comm. ExecuteNonQuery (); Conn. Close (); returnR//return to execution results } } /*how to ask Hovertree.com*//**************** test Class key code ***************/Department Dept=NewDepartment ("Development Department","responsible for product development."); Adomanager Manager=NewAdomanager (); intR =Manager. Save (dept); Console.WriteLine (R==0?"failed":"Success");
Summary:
C # attribute classes are the same as meta annotations in Java
The nature of the feature is a class that inherits the attribute
Use enable to omit attribute endings, such as: Tableattribute =>> Table
The compile and run process of the target element that will affect its role
To use custom attributes:
1. Defining attribute classes, classes must inherit the Word attribute class directly or indirectly
2. Add an attribute on the target element of the attribute that needs to be used
3. Use of classes with added attributes to obtain and use information from specific attributes
Recommendation: http://www.cnblogs.com/roucheng/p/dushubiji.html
C # custom Attribute instances