To have a dynamic assignment or value to a property or field of an instance of a type, you first have to get the type of that instance, or the types, Microsoft has provided us with enough methods.
first, set up a test class
Copy CodeThe code is as follows:
public class MyClass
{
public int one {set;
public int two {set; get;}
public int five {set; get;}
public int three {set; get;}
public int four {set; get;}
}
then write the code that reflects the class
Copy CodeThe code is as follows:
MyClass obj = new MyClass ();
Type t = typeof (MyClass);
Loop Assignment
int i = 0;
foreach (var item in t.getproperties ())
{
Item. SetValue (obj, I, null);
i + 1;
}
Assign values individually
T.getproperty ("Five"). SetValue (obj, 11111111, null);
Loop fetch
StringBuilder sb = new StringBuilder ();
foreach (var item in t.getproperties ())
{
Sb. Append ("type:" + item.) Propertytype.fullname + "Property name:" + Item. Name + "Value:" + Item. GetValue (obj, null) + "<br/>");
}
Individual values
int five = Convert.ToInt32 (T.getproperty ("Five"). GetValue (obj, null));
Sb. Append ("Five value alone:" + five);
string result = sb. ToString ();
Response.Write (Result);
Test Display results:
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
Value of five alone: 11111111
Well, once you know the properties of a class are reflected, you may be able to think of a way to do it, that is, T. GetProperties () changed to T. GetMethods (), Operation Method Ditto.