Example code in C # that uses reflection and attribute simplification

Source: Internet
Author: User

Suppose there is now a student class (Student)


                                    {  {name = Age                    {;                     Address {;

If you need to determine if some fields (properties) are empty, or if they are greater than 0, the following code is available:


public static string Validatestudent (Student Student)        {            StringBuilder validatemessage = new StringBuilder ();                        if (string. IsNullOrEmpty (student. Name)            {                validatemessage.append ("cannot be empty");            }            if (string. IsNullOrEmpty (student. Sex)            {                validatemessage.append ("Gender cannot be empty");            }            if (student. Age <= 0)            {                validatemessage.append ("required is greater than 0");            }                        //...... Hundreds of lines                        //write here to find the wrong ah, if the required fields have more than 20, I would like to write it all the time!            return validatemessage.tostring ();        }

This kind of code, reusability is not high, and inefficient.

We can use attributes, reflection, and then traverse the properties and examine the attributes.

First, customize a "required" attribute class, inheriting from attribute


    <summary>    ///"required" feature, inherited from attribute    ///</summary> public sealed class Requireattribute: Attribute    {        private bool isrequire;        public bool Isrequire        {            get {return isrequire;}        }        <summary>///constructors///</summary>//        <param name= "Isrequire" ></param> Public        Requireattribute (bool isrequire)        {            this.isrequire = Isrequire;        }    }

Then use this custom attribute to mark the student class's member properties:


<summary>///Students///    </summary> public    class Student    {        //<summary> Name////        </summary>        private string name;        [Require (True)]        public string name        {            get {return Name;}            set {name = value;}        }        <summary>        ///Age        ///</summary> [Require (true)] public        int ages {get; set;}        <summary>        //        /Address        ///</summary> [Require (false)] public        string Address {get; set;} //        <summary>        //Gender        ///</summary> [Require (true)] public         string sex;    

To check the properties of a class by attributes:


  <summary>///check method, support generics///</summary>//<typeparam name= "T" ></typeparam >//<param name= "instance" ></param>//<returns></returns> public Stati                    C String Checkrequire<t> (T instance) {var validatemsg = new StringBuilder ();                        Gets the properties of the T class type T = typeof (T);                        var Propertyinfos = t.getproperties ();                Traversal property foreach (Var propertyInfo in Propertyinfos) {//check whether the attribute is marked by a property Requireattribute attribute = (requireattribute) attribute.getcustomattribute (PropertyInfo, typeof (Requireattribu                                TE));                No tag, skip directly if (attribute = = null) {continue; }//Gets the data type of the property var type = Propertyinfo.propertytYpe. ToString ().                                ToLower ();                                Gets the value of the attribute var = propertyinfo.getvalue (instance); if (type. Contains ("System.String")) {if (string. IsNullOrEmpty (String) value && attribute. Isrequire) Validatemsg.append (propertyinfo.name). Append ("Cannot be empty").                Append (","); } else if (type. Contains ("System.int")) {if ((int) value = = 0 && attribute. Isrequire) Validatemsg.append (propertyinfo.name). Append ("must be greater than 0").                Append (",");        }} return validatemsg.tostring (); }

Perform validation:


static void Main (string[] args)        {            var obj = new Student ()            {                Name = ""            };            Console.WriteLine (Checkrequire (obj));            Console.read ();        }

Result output:

Some people will find that sex also marks [Require (true)], why there is no authentication information, because sex does not implement the property {get; set;},getproperties is not available

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.