1. Create attributes
[AttributeUsage( | , AllowMultiple = true, Inherited = true)] //AttributeTargets: The target type to which the attribute is applied. AllowMultiple: Whether to allow multiple this attributes to be applied in one element. Inherited: Can attributes be inherited by derived classes?public class CodeStatusAttribute : Attribute { private string status; public CodeStatusAttribute(string status)//Constructor is positional parameter { = status; } public string Tester { set; get; }//Properties and public fields are named parameters public string Coder { set; get; } public override string ToString() { return status; } }
2. Application properties
//1. Use a single attribute[CodeStatus("Plain a")] public class Tringe { } //2. Use multiple attributes[CodeStatus("B version", Coder = "Little Li")] [CodeStatus("B version", Coder = "Xiao Wang")] //It is also possible [CodeStatus("aa",Coder="Xiao Li"),CodeStatus("aa",Coder="Xiao Wang")]public class Square { } //3. Use positional parameters and named parameters//type means what element this property is associated with, which may include: assembly, field, method, param, property, return, moudule, event, type, etc. .[type: CodeStatus("Final Edition", Coder = "Little Li", Tester = "Old Li")] public class Circle { [CodeStatus("Final Edition", Coder = "Little Li", Tester = "Old Li")] public Circle() { } }
3. Reflection properties
//1. Get the attributes on the class.Type t = typeof(Circle); Attribute[] attArr = (t, typeof(CodeStatusAttribute)); //orobject[] attArr1 = (typeof(CodeStatusAttribute), true); //2. Get the attributes on the memberAttribute[] attArr3 = ()[0].GetCustomAttributes().ToArray();//Constructor, get field GetField("..") //3, traversalforeach (Attribute attr in attArr3) { CodeStatusAttribute item = (CodeStatusAttribute)attr; (() + + ); }
4. Net built-in properties
[Condeitonal] //Condition control[Obsolete] //Abandoned attributes[Serializable]//Serializable properties[AssemblyDelaySign] //Assembly delay signature
This is all about this article about C# attributes. I hope it will be helpful to everyone's learning and I hope everyone will support me more.