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 and assign a value to the attribute of the Real-column object:
User u = new user ();
U. Name = "ahbool ";
U. Gender = "male ";
// Output the values of all attribute names and attributes of this class.
Response. Write (getproperties (u ));
// The output result is: Name: ahbool, Gender: male, age :,
// Retrieve the attributes and 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;
}