C # basic -- Attribute and reflect applications

Source: Internet
Author: User

C # basic -- Attribute and reflect applications
1. attribute definition and function: when running in a common language, you can add a description declaration similar to a keyword, called attributes. It marks elements in a program, such as types, fields, methods, and attributes. Attributes and Microsoft. the metadata of the. NET Framework file is stored together and can be used to describe your code at runtime, or affect the behavior of the application when the program is running. for example, serialization is commonly used in WCF. For example, the added [DataMenber] is a tag. And xml serialization. 2. The definition and function reflection of Reflect can be used to observe and modify the execution of the program at runtime. A reflection-oriented program component can monitor code execution within a certain range and modify itself based on the desired target range. This is usually done by dynamically allocating program code at runtime. In an object-oriented programming language such as Java, Reflection allows you to check classes, interfaces, fields, and methods at runtime without knowing the Interface Name, fields, and methods during compilation. It also allows instances to create new objects and call methods. (Excerpted to Wikipedia). In fact, it can be simply understood that through reflection, you can easily obtain the status of all method attribute fields in a class. 3. the following example shows how to easily understand reflection and Attribute applications. the business background is as follows: there is a Person object. Currently, only the Name and Num attributes are available, and then the validity of the Person object must be verified using methods. Judgment Rules: 1. name is required. If Name is empty, the system prompts "Name cannot be blank"; 2. num can be null, but data must be composed of numbers. If it is a non-numeric string, "Incorrect format" is displayed ". 3. address can be blank. If there is data, the length cannot exceed 12. If it exceeds 12, the system prompts "the Address length cannot exceed 12". For the Person class, in the future, familiar Judgment Rules may change, and attributes may be added to reduce the number of attributes. 4. solution 1: You may think of conventional solutions. Currently, there are only three attributes: Name, Address, and Num. Each time I write three code segments to verify the attributes of Name, Address, and Num respectively. If an attribute is added, for example, the public attribute EmailAddress is added, you must add the verification string as the email code. If an attribute is deleted, you can delete the code that determines whether the property is qualified. This is also the method I first came up. However, the maintainability is poor. The change is too big. And it will lead to repeated code. If you want to change to Address, you cannot leave it blank. Then, when determining whether the address is valid, add the statement to determine whether the address cannot be empty. 5. solution 2: To solve the problem of solution 1, we can actually implement it through Attribute and reflection. The idea is as follows: 5.1 first we create a PersonCheckAttribute object, which inherits from the System. attribute. copy the code using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ReflectTest. model {public class PersonCheckAttribute: Attribute {// three bool variables are used to determine whether to verify the information private bool checkEmpty = false; // whether the private bool checkMaxLength is empty = false; // maximum length: private bool checkRegex = false; // use regular Expression verification parameters (mailbox, whether to brush the number) private int maxLength = 0; private string regexStr = string. empty; public bool CheckEmpty {get {return this. checkEmpty;} set {this. checkEmpty = value ;}} public bool CheckMaxLength {get {return this. checkMaxLength;} set {this. checkMaxLength = value ;}} public bool CheckRegex {get {return this. checkRegex;} set {this. checkRegex = value ;}} public int MaxLength {get {Return this. maxLength;} set {this. maxLength = value ;}} public string RegexStr {get {return this. regexStr;} set {this. regexStr = value ;}}} copy code 5.2 and then add the Person class. Note the labels. Tips: I tagged it. For the 5.1 PersonCheckAttribute class, the bool variable is used to determine whether verification is required, and the public attribute is used to access the judgment parameter. Copy the code using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ReflectTest. model {public class Person {[PersonCheck (CheckEmpty = true)] public string Name {get; set;} [PersonCheck (CheckRegex = true, regexStr = "^ [0-9] * [1-9] [0-9] * $")] public string Num {get; set ;} [PersonCheck (CheckMaxLength = true, MaxLength = 12)] public string Add Ress {get; set ;}}copy code 5.3 attributes. Let's take a look at how to obtain the public attributes of the class through reflection and the attributes of each Attribute. Copy the code using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using ReflectTest. model; using System. reflection; using System. text. regularExpressions; namespace ReflectTest. business {public class PersonCheck {// get all error messages public static string GetErrorMessage (Person person) {PropertyInfo [] propertyInfos = Person. getType (). getProperties (); // get a class String errorMsg = string. empty; // traverse all public attributes (Name, Num, Address) foreach (PropertyInfo info in propertyInfos) {errorMsg + = GetSignalPropertity (info, person);} return errorMsg ;} // obtain the Attribute of a single public Attribute. that is, the [PersonCheck] information in the model class is private static string GetSignalPropertity (PropertyInfo propertyInfo, Person person) {// for this example, each Properties (attribute) there is only one Attribute (TAG), so first () is used for obtaining. // However, you must add [PersonCheck] label, but the fields in the expression can be not set. because no. getCustomAttributes () returns null. an error will be reported if you point to first. personCheckAttribute attribute = propertyInfo. getCustomAttributes (). first () as PersonCheckAttribute; string errorMsg = string. empty; // The following if statement is used to determine the settings in the tag. if (attribute. checkEmpty) {string obj = propertyInfo. getValue (person) as string; if (string. isNullOrEmpty (obj) {errorMsg + = Environment. newLine + string. Format ("{0} cannot be blank", propertyInfo. name) ;}} if (attribute. checkMaxLength) {string obj = propertyInfo. getValue (person) as string; if (obj! = Null & obj. length> attribute. maxLength) {errorMsg + = Environment. newLine + string. format ("{0} maximum length: {1}", propertyInfo. name, attribute. maxLength) ;}}// you can use the regular expression if (attribute. checkRegex) {string obj = propertyInfo. getValue (person) as string; Regex regex = new Regex (attribute. regexStr); if (obj! = Null &&! Regex. IsMatch (obj) {errorMsg + = Environment. NewLine + string. Format ("{0} Format incorrect", propertyInfo. Name) ;}} return errorMsg ;}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.