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 keyword-like description declaration called attributes, which 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. Definition and function of Reflect

Reflection can be used to observe and modify program execution 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. In order to better understand reflection and Attribute application, the following example is provided.

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 blank, the system prompts "Name cannot be blank ";

2. Num can be null, but it must be composed of numbers if there is data. If it is a non-numeric string, "Incorrect format" is displayed ".

3. The 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"

Consider: For the Person class, the familiar Judgment Rules may change in the future, or attributes may be added to reduce 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 System. Attribute.

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 a regular expression to verify the parameter (whether to use a mailbox or a 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 ;}}}}

5.2 then we will 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.
  

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 Address { get; set; }    }}

5.3 attributes have been completed. Let's take a look at how to obtain the public attributes of the class through reflection and the attributes of each Attribute.

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 (); // obtain all attributes of 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 [Person Check] 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. forma T ("{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 ;}}}

5.4 The running result is shown below.

5.4.1 if Person p = new Person () {Num = "abc"}; call the GetErrorMessage (Person person) method and the running result is as follows. Person cannot be blank.

5.4.2 if Person p = new Person () {Num = "123", Address = "chengdu, Tianfu SoftwarePark"}; call the GetErrorMessage (Person person) method and the running result is as follows. Person cannot be blank.

  

6. analyze the advantages of reflection:

If you need to modify the Address, the Address cannot be blank. I only need to set CheckEmpty = true in the Address label, without modifying the logic code again. Similarly, if you want to add the EmailAddress attribute to the Person class, you only need to add the EmailAddress attribute to the Person class to set the label to [PersonCheck (CheckRegexStr = true, regexStr = "*")], * The system does not determine whether the regular expression is valid or not.

 

7. Conclusion:

In fact, the younger brother is also new to reflection. There are a lot of things that are easy to understand. At present, we know so much about reflection. If you have any good ideas or materials, please share them and learn from each other. Code link: http://download.csdn.net/detail/u010093618/8088327

 

  


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

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.