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 ;}