C # retrieving object class property names and values | traversing class objects

Source: Internet
Author: User

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

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.