Attribute is a very important technology in C# programming, with a wide range of applications and flexible and varied usage. This article analyzes the application of attributes in C# in an example form. Specific entry:
1. Scope of application
Assembly, module, type (class, structure, enumeration, interface, delegate), fields, methods (including construction), methods, parameters, method return value, attribute (property), Attribute
[AttributeUsage()] public class TestAttribute : Attribute { } [TestAttribute]//structure public struct TestStruct { } [TestAttribute]//enumerate public enum TestEnum { } [TestAttribute]//Class public class TestClass { [TestAttribute] public TestClass() { } [TestAttribute]//Field private string _testField; [TestAttribute]//property public string TestProperty { get; set; } [TestAttribute]//Method [return: TestAttribute]//Define the return value writing method public string TestMethod([TestAttribute] string testParam)//In the parameters { throw new NotImplementedException(); } }
Here we give the definition of commonly used Atrrites other than assemblies and modules.
2. Customize Attribute
In order to comply with the requirements of the "Common Language Specification (CLS), all custom Attributes must be inherited.
Step 1: Customize an Attribute that checks the length of the string
[AttributeUsage()] public class StringLengthAttribute : Attribute { private int _maximumLength; public StringLengthAttribute(int maximumLength) { _maximumLength = maximumLength; } public int MaximumLength { get { return _maximumLength; } } }
AttributeUsage provides an Attribute that defines the scope of the custom Attribute. Here we only allow this Attribute to be used on Property, and a built-in constructor with parameters is allowed to pass the maximum length required by external input.
Step 2: Create an entity class to run our custom properties
public class People { [StringLength(8)] public string Name { get; set; } [StringLength(15)] public string Description { get; set; } }
Two string fields Name and Description are defined. Name requires a maximum length of 8, and Description requires a maximum length of 15.
Step 3: Create a validated class
public class ValidationModel { public void Validate(object obj) { var t = (); // Since we only set Attute in Property, we first get Property var properties = (); foreach (var property in properties) { //This is only a stringlength verification. If you want to do a lot of verification here, you need to design it carefully. Never use if elseif to link //It will be very difficult to maintain. There are many open source projects like this. If you are interested, you can read the source code. if (!(typeof(StringLengthAttribute), false)) continue; var attributes = (); foreach (var attribute in attributes) { //The MaximumLength here is best done with constants var maxinumLength = (int)(). GetProperty("MaximumLength"). GetValue(attribute); //Get the value of the attribute var propertyValue = (obj) as string; if (propertyValue == null) throw new Exception("exception info");//You can customize it here, or use specific system exception classes if ( > maxinumLength) throw new Exception(("property{0}Value of{1}The length exceeds{2}", , propertyValue, maxinumLength)); } } } }
Reflection is used here, because Attribute is generally used with reflection. Here we verify whether the string length exceeds the required one. If it exceeds it, an exception will be thrown.
private static void Main(string[] args) { var people = new People() { Name = "qweasdzxcasdqweasdzxc", Description = "description" }; try { new ValidationModel().Validate(people); } catch (Exception ex) { (); } (); }
I hope that the examples described in this article will be of some help to everyone's C# programming design.