To dynamically assign values or values to attributes or fields of A Type instance, you must first obtain the instance or Type. Microsoft has provided enough methods for us.
First, create a test class.
Copy codeThe Code is as follows: public class MyClass
{
Public int one {set; get ;}
Public int two {set; get ;}
Public int five {set; get ;}
Public int three {set; get ;}
Public int four {set; get ;}
}
Then write code that reflects the class
Copy codeThe Code is as follows: MyClass obj = new MyClass ();
Type t = typeof (MyClass );
// Cyclic assignment
Int I = 0;
Foreach (var item in t. GetProperties ())
{
Item. SetValue (obj, I, null );
I + = 1;
}
// Assign values separately
T. GetProperty ("five"). SetValue (obj, 11111111, null );
// Obtain it cyclically
StringBuilder sb = new StringBuilder ();
Foreach (var item in t. GetProperties ())
{
Sb. append ("type:" + item. propertyType. fullName + "attribute name:" + item. name + "value:" + item. getValue (obj, null) + "<br/> ");
}
// Separate values
Int five = Convert. ToInt32 (t. GetProperty ("five"). GetValue (obj, null ));
Sb. Append ("take the five value separately:" + five );
String result = sb. ToString ();
Response. Write (result );
Test result:
Type: System. Int32 property name: one value: 0
Type: System. Int32 property name: two value: 1
Type: System. Int32 property name: five value: 11111111
Type: System. Int32 property name: three Value: 3
Type: System. Int32 property name: four value: 4
Take the five value separately: 11111111
Well, after learning about the use of class property reflection, you may think of the same method, that is, t. change GetProperties () to t. getMethods (). The operation method is the same as above.