Tips for using reflection to traverse an object's properties and values in C #

Source: Internet
Author: User
Tags foreach reflection

This article mainly introduces the use of reflection in C # to traverse an object properties and values of the trick, which should be very useful, this article directly gives the example code, the need for friends can refer to the

Summarize:

An instantiated object TC for a class that iterates through the method (with reflection) that gets all the attributes (Child members):

The code is as follows:

Type t = tc. GetType ()//Get the type of the class

Then use Type.getproperties to get propertyinfo[], and then you can use foreach to traverse the

foreach (PropertyInfo pi in T.getproperties ())

{

Object value1 = Pi. GetValue (TC, NULL));//with PI. GetValue Get Value

String name = Pi. name;//gets the name of the attribute, and then it can be judged by the name to do what you want.

Gets the type of the property, makes a judgment, and then makes a subsequent operation, such as determining that the obtained property is an integer

if (value1. GetType () = = typeof (int))

{

Do the things you want to do

}

}

Attention:

You must set the properties of the get and set methods before reflection gets the property

The code is as follows:

public int Pid

{

get {return PID;}

set {pid = value;}

}

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.