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