C # Attribute usage instance parsing,
Attribute is a very important technology in C # programming. It has a wide range of applications and flexible usage. This article analyzes the application of attributes in C # as an example. Specific scenes:
I. Scope of application
Assembly, module, type (class, structure, enumeration, interface, delegate), field, method (including constructor), method, parameter, method return value, property, Attribute
[AttributeUsage (AttributeTargets. all)] public class TestAttribute: attribute {} [testattrict] // structure public struct TestStruct {} [testattrict] // enumerate public enum TestEnum {} [TestAttribute] // public class TestClass {[TestAttribute] public testClass () {} [TestAttribute] // FIELD private string _ testField; [TestAttribute] // attribute public string TestProperty {get; set;} [TestAttribute] // [return: testattrition] // define the return value in public string TestMethod ([TestAttribute] string testParam) // {throw new NotImplementedException ();}}
Here we provide the definition of Atrribute, which is commonly used in addition to programming sets and modules.
Ii. custom Attribute
To comply with the "CLS" requirements, all custom attributes must inherit System. Attribute.
Step 1: customize an Attribute to check the string length
[AttributeUsage(AttributeTargets.Property)]public class StringLengthAttribute : Attribute{ private int _maximumLength; public StringLengthAttribute(int maximumLength) { _maximumLength = maximumLength; } public int MaximumLength { get { return _maximumLength; } }}
AttributeUsage is an Attribute provided by the system to limit the scope of the custom Attribute. Here, we only allow this Attribute to be applied to the Property and create a constructor with parameters, specifies the maximum length required for external input.
Step 2: Create an object class to run our custom attributes
public class People{ [StringLength(8)] public string Name { get; set; } [StringLength(15)] public string Description { get; set; }}
Two string fields, Name and Description, must be 8 characters in length and 15 characters in length.
Step 3: Create a verified class
Public class ValidationModel {public void Validate (object obj) {var t = obj. getType (); // because we only set attivity in Property, we first get Property var properties = t. getProperties (); foreach (var property in properties) {// only perform a stringlength verification here. If you need to perform a lot of verification here, make a good design, do not 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 look at the source code. If (! Property. isDefined (typeof (StringLengthAttribute), false) continue; var attributes = property. getCustomAttributes (); foreach (var attribute in attributes) {// MaximumLength here is best to use constants for var maxinumLength = (int) attribute. getType (). getProperty ("MaximumLength "). getValue (attribute); // obtain the attribute value var propertyValue = property. getValue (obj) as string; if (propertyValue = null) throw new Exception ("exception info"); // you can customize it here, you can also use the specific system exception class if (propertyValue. length> maxinumLength) throw new Exception (string. format ("the length of the {0} value {1} exceeds {2}", property. name, propertyValue, maxinumLength ));}}}}
Reflection is used here, because Attribute is generally used together with reflection, which verifies whether the length of the string exceeds the required value. If it exceeds the value, an exception is thrown.
private static void Main(string[] args){ var people = new People() { Name = "qweasdzxcasdqweasdzxc", Description = "description" }; try { new ValidationModel().Validate(people); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine();}
I hope the examples described in this article can help you with C # programming.