C # basics --- Attribute and reflect application 2,

Source: Internet
Author: User

C # basics --- Attribute and reflect application 2,

I have previously written an article about labeling and reflection. It is mainly used for field verification in the class. The following links C # basic --- Attribute and reflect applications. This project iteratively finds that the company's project finds that the old Code has made a small framework for business expansion by tagging and reflection, which is quite practical. So I thought about it and moved it to the blog garden. It may not be well written. Please kindly advise.

Background: [it seems inappropriate to simulate a background for convenience, but I wrote this in my Demo. Of course, it is not perfect compared with the company]

Everyone eats, but the eating habits in every country are different. Chinese eat dumplings, Canadian eat pasta, American eat turkey. People from other countries eat other things. How can we maintain different customs in different countries. I opened a restaurant with food in China, the United States, and Canada. If a person comes, how can we let the program determine his or her nationality automatically. This requires tag and reflection. Let's take a look at the Demo.

1. entity class.

First, we define a base class. In the Person base class, virtual methods are defined. Everyone will eat.

Person (Country = PersonCountry. UNKnown)] public class Person {public virtual void Eat () {Console. WriteLine ("Let's Eat ");}}

Again, people in different countries inherit the base class and rewrite the eat method to reflect the eating habits of different countries.

[Person (Country = PersonCountry. USA)] public class USA: Person {public override void Eat () {Console. writeLine ("we eat turkey");} [Person (Country = PersonCountry. china)] public class Chinese: Person {public override void Eat () {Console. writeLine ("Let's eat dumplings");} [Person (Country = PersonCountry. USA)] public class USA: Person {public override void Eat () {Console. writeLine ("Let's eat turkey ");}}

2. Labels
To distinguish the persons in the country of each class, we set a Person tag and the PersonCountry enumeration.

    public class PersonAttribute:Attribute    {        private PersonCountry _country = PersonCountry.UNKnown;        public PersonCountry Country        {            get            {                return _country;            }            set            {                this._country = value;            }        }    }    public enum PersonCountry    {        USA,        China,        Canada,        UNKnown    }

3. Helper method:
Entity classes and enumerations have been defined. So how can we let the program automatically differentiate people's nationality and then confirm their eating habits. The following can be determined through reflection.

A. Assembly. GetExecutingAssembly () can obtain the current program level. assembly. GetTypes () can obtain all types, including USA, Canda, and Chinese information.

B. (PersonAttribute) Attribute. GetCustomAttribute (currentType, typeof (PersonAttribute); obtain the tag of the current class, and then compare the tag with the passed countryType to confirm the Person type.

C. Create an object through InvokeMember and return

public class PersonHelper    {        public static Person GetPersonObj(PersonCountry contryType)        {            Assembly assembly = Assembly.GetExecutingAssembly();            Type[] typeList = assembly.GetTypes();            foreach (Type currentType in typeList)            {                                var attribute = (PersonAttribute)Attribute.GetCustomAttribute(currentType, typeof(PersonAttribute));                if (attribute!=null && attribute.Country == contryType)                {                    return currentType.InvokeMember(null, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, new object[] { }) as Person;                }                             }            return new Person();        }    }

4. Test method:
We may have been confused before. Let's take a look at the test below, and we may be quite clear:

Note: 1. If the new user is Chinese, you only need to call the Helper method and obtain the Chinese object, and then execute the corresponding eat method.

2. If we want to know about Korean eating habits, we only need to add one more class and then add the corresponding label.

Public static void Main (string [] args) {Person p1 = PersonHelper. getPersonObj (PersonCountry. china); p1.Eat (); // output: We eat dumplings Person p2 = PersonHelper. getPersonObj (PersonCountry. canada); p2.Eat (); // output: pasta for us}

5. Conclusion:

The examples described in this blog are far-fetched, but I just feel that this idea is still good. This facilitates project expansion. I hope it will be useful to you. I also want to write this blog to review reflection and tag usage.

 

 

  

 

  

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.