To dynamically assign or take values to attributes or fields of an instance of type, you must first get the Type of this instance or type. Microsoft has provided us with enough methods.
First create a test class
Copy the 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 the codeThe code is as follows:
MyClass obj = new MyClass();
Type t = typeof(MyClass);
//Cyclic assignment
int i = 0;
foreach (var item in ())
{
(obj, i, null);
i += 1;
}
//Assign individually
("five").SetValue(obj, 11111111, null);
//Loop acquisition
StringBuilder sb = new StringBuilder();
foreach (var item in ())
{
("Type:" + + "Attribute name:" + + "Value:" + (obj, null) + "<br />");
}
//Select values
int five = Convert.ToInt32(("five").GetValue(obj, null));
("Fetch the value of five separately:" + five);
string result = ();
(result);
Test results show:
Type: System.Int32 Property name: one Value: 0
Type: System.Int32 Property name: two Value: 1
Type: System.Int32 Property name: five Value: 111111111
Type: System.Int32 Property name: three Value: 3
Type: System.Int32 Property name: four Value: 4
Take the value of five separately: 1111111111
Okay, after understanding the use of the attribute reflection of the class, you may think that the method can also be done, that is, change () to (), and the operation method is the same as above.