C # leverages reflection to iterate over all property names of a class and the values of all properties of that class's instance

Source: Internet
Author: User

Turn from Goldeneyezhang original C # use reflection to traverse to get all the property names of a class, and the values of all the properties of that class's instance

C # leverages reflection to iterate over all the property names of a class and the values of all the properties of that class's instance:

The object that corresponds to the instantiation of a class TC, traversing the method that gets all the attributes (Child members) (with reflection):

Type t = tc. GetType ();//gets the type of the class//Then use type.getproperties to get propertyinfo[], and then you can use foreach to iterate through theforeach(PropertyInfo Piincht.getproperties) {Objectvalue1 = Pi. GetValue (TC,NULL));//with Pi. GetValue Get Value    stringname = Pi. Name;//get the name of the property, then you can do what you want by the name .//gets the type of the property, makes a judgment, and then makes subsequent operations, such as determining that the obtained property is an integer    if(value1. GetType () = =typeof(int)) {//make the action you want    }}

Attention:

The properties of the get and set methods must be set for reflection to get the property

public int Pid{get {return Pid;} set {pid = value;}}

C # leverages reflection to iterate over all property names of a class and the values of all properties of that class's instance

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.