Tips for Traversing attributes and values of an object Using Reflection in C #

Source: Internet
Author: User

Tips for Traversing attributes and values of an object Using Reflection in C #

This article describes how to use reflection to traverse the attributes and values of an object in C #. This is useful in most cases. This article provides the instance Code directly. For more information, see

Summary:

Corresponding to the instantiated object tc of a class, traverse the method for getting all attributes (sub-members) (Using Reflection ):

The Code is as follows:

Type t = tc. GetType (); // obtain the Type of this class

// Use Type. GetProperties to obtain PropertyInfo [], and then you can use foreach to traverse it.

Foreach (PropertyInfo pi in t. GetProperties ())

{

Object value1 = pi. GetValue (tc, null); // use pi. GetValue to obtain the value

String name = pi. Name; // obtain the attribute name. You can determine the Name to perform the operations you want.

// Obtain the attribute type, perform judgment, and perform subsequent operations. For example, the obtained attribute is an integer.

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

{

// Perform the operation you want

}

}

Note:

The get and set attributes must be set before reflection can obtain the attributes.

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.