The role of reflection presumably we all know, a small number of properties of the automated operation of the manual add a few of course there is no problem, but the number of properties of the time to knock the code can be trapped, and the extension and maintainability caused a lot of, and the following code if not directly use please add using System.Text; a reference.
To dynamically assign or value a property or field of an instance of a type, you first have to get the type of this instance, or types, that Microsoft has provided us with enough methods.
First, set up a test class
Public classMyClass { Public intOne {Set;Get; } Public intBoth {Set;Get; } Public intFive {Set;Get; } Public intThree {Set;Get; } Public intFour {Set;Get; } }
Then write the code that reflects the class
MyClass obj =NewMyClass (); Type T=typeof(MyClass);//Cyclic Assignmentinti =0; foreach(varItemincht.getproperties ()) {Item. SetValue (obj, I,NULL); I+=1; } //Assigning values individuallyT.getproperty ("Five"). SetValue (obj,11111111,NULL); //Loop GetStringBuilder SB =NewStringBuilder ();foreach(varItemincht.getproperties ()) {sb. Append ("Type:"+ Item. Propertytype.fullname +"Property Name:"+ Item. Name +"values:"+ Item. GetValue (obj,NULL) +"<br/>"); } //Individual Valuesintfive = Convert.ToInt32 (T.getproperty ("Five"). GetValue (obj,NULL)); Sb. Append ("to take five values individually:"+five); stringresult =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
The value of five is taken separately: 11111111
Well, once you understand the properties of a class, you might think of a way to do this, or T. GetProperties () instead of T. GetMethods (), the operation method is the same as above.
Simple operations for C # Reflection technology (Reading and setting properties of classes)