C # How to obtain object class property names and values and traverse class objects,

Source: Internet
Author: User

C # How to obtain object class property names and values and traverse class objects,
C # tutorial on retrieving object class property names and values and traversing class objects

Retrieve all attribute names of an object class and the values of all attributes of this class through traversal.

// Define a class first:

Public class User {public string name {get; set;} public string gender {get; set;} public string age {get; set ;}// instantiate the class, assign a value to the attribute of the real-name object: User u = new User (); u. name = "ahbool"; u. gender = "male"; // output all the property names and values corresponding to the property Response. write (getProperties (u); // The output result is: name: ahbool, gender: male, age:, // obtain the attributes and attribute values of the class through traversal: public string getProperties (T t) {string tStr = string. empty; if (t = null) {return tStr;} System. reflection. propertyInfo [] properties = t. getType (). getProperties (System. reflection. bindingFlags. instance | System. reflection. bindingFlags. public); if (properties. length <= 0) {return tStr;} foreach (System. reflection. propertyInfo item in properties) {string name = item. name; object value = item. getValue (t, null); if (item. propertyType. isValueType | item. propertyType. name. startsWith ("String") {tStr + = string. format ("{0 }:{ 1},", name, value) ;}else {getProperties (value) ;}} return tStr ;}

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.