C # base--attribute (label) and reflect (reflection) applications

Source: Internet
Author: User

1.Attribute definition and function: The common language runtime allows you to add a descriptive declaration of a similar keyword, called attributes, that labels elements in your program, such as types, fields, methods, and properties. The metadata for attributes and Microsoft. NET framework files can be used to describe your code to the runtime, or to affect the behavior of your application as the program runs. For example, serialization is commonly used in WCF. For example, adding [Datamenber] is a label. and XML serialization is the same. The definition and function reflection of 2.Reflect can be used to observe and modify the execution of the program at run time. A reflection-oriented program component can monitor the execution of a range of code and can modify itself according to the scope of the desired target associated with this. This is usually achieved by dynamically allocating program code at run time. In object-oriented programming languages such as Java, Reflection allows classes, interfaces, fields, and methods to be inspected at run time without knowing the name of the interface, fields, methods, and so on during compilation. It also allows the instantiation of new objects and methods of invocation. (excerpt to Wikipedia). In fact, it can be easily understood that by reflection it is easy to get all the method attribute field states in a class. 3. For more convenient understanding of reflection and the application of attribute, here is an example. The business background is as follows: There is a person object, currently only the name and NUM attributes, and then the method is used to verify the legality of the man object. Rule: 1.Name is required, if name is empty, then the hint "name cannot be empty";         2.Num can be empty, but if you have data, it must consist of numbers, and if a non-numeric string pops up "malformed". 3.Address can be empty, if there is no longer than 12 of the data, if more than 12 indicates that "Address length cannot exceed 12" need to consider: for the person class, the later familiar judgment rule may change, may also increase the attribute, reduces the attribute. 4. Solution One: For conventional solutions, you might think of it. Currently only name,address,num three properties, each time I write three pieces of code to verify Name,address,num respectively. If you add a property, such as adding a public property emailaddress, you have to include the code that verifies whether the string is a mailbox, and if you delete a property, the code that determines whether the property is qualified is removed from judgment. This is also my first thought of the method. However, this is not a good place to be maintainable. The change is too big. It also causes duplicate code. If the need to change to address can not be empty. So in the judgment address isWhen the legality of the time to add to the judgment can not be empty case. 5. Solution two: In order to solve the problem of the solution, we can actually achieve through attribute and reflection. The idea is as follows: 5.1 First we create a Personcheckattribute object that he inherits with System.Attribute. Copy 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 if there is a private bool to verify this information Checkempty = false; Whether the empty private bool Checkmaxlength = false; Maximum length private bool Checkregex = false; Verify the parameter with regular expression (is the 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 {g ET {return this.checkmaxlength;} set {this.checkmaxlength = value;}} public bool Checkregex {get {return This.checkregex;} set {This.checkregex = value,}} public int MaxLength {get {R Eturn this.maxlength; } set {this.maxlength = value;}} public string Regexstr {get {return this.regexstr;} set {This.regexSTR = value; }}}} Copy code 5.2 and then we'll add the person class. Notice the label inside.   Tips: I tagged it, for the 5.1 Personcheckattribute class, the bool variable is used to determine if validation is needed, and public properties are used to access the judging parameters. Copy 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 =)] public string Address {get; set;}}} Copy Code 5.3 Properties are done, here's how to get the public properties of the class through reflection, and the attribute of each property. Copy 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 prompts public static string GetErrorMessage {propertyinfo[] Propertyinfos = person. GetType (). GetProperties (); //Gets all properties of a class string errormsg = String. Empty; For all common properties (name,num,address) traversal foreach (PropertyInfo info in Propertyinfos) {errormsg + = getsignalpropertity (info, person); } return errormsg; }//Gets the attribute of a single public property. That is, the [Personcheck] information inside the model class is private static string getsignalpropertity (PropertyInfo Propertyinfo,person person) {//Because for this example, each properties (property) has only one attribute (label), so it is obtained with first (),//But one thing is that it must be added in the attribute [ Personcheck] Label, but you can not set the field inside the emoticon. Because there is no. GetCustomAttributes () returns NULL. Pointing to first will cause an error. Personcheckattribute attribute = Propertyinfo.getcustomattributes (). First () as Personcheckattribute; String errormsg = String. Empty; The following if statement is the determination of the settings inside the label, what is set to perform what data check if (attribute. Checkempty) {String obj = Propertyinfo.getvalue (person) As String, if (string. IsNullOrEmpty (obj)) {errormsg + = Environment.NewLine + string. Format ("{0} cannot be empty", 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 is {1}", Propertyinfo.name, attribute. MaxLength); }}//For judging the digital mailbox can be passed 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} not formatted", propertyinfo.name); }} return errormsg; } }}

C # Base--attribute (tags) and reflect (reflection) applications

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.