Simple operation of C reflection technique of reads and sets the properties of the class

  • 2020-05-12 02:25:59
  • OfStack

To dynamically assign or value a property or field to an instance of a type, you first need to get Type of that instance or type, and Microsoft has provided us with plenty of ways to do so.
First, create a test class

 
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 you write the code that reflects that class
 
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; 
} 
// A separate assignment  
t.GetProperty("five").SetValue(obj, 11111111, null); 
// Loop gain  
StringBuilder sb = new StringBuilder(); 
foreach (var item in t.GetProperties()) 
{ 
sb.Append(" Type: " + item.PropertyType.FullName + "  The property name: " + item.Name + "  Value: " + item.GetValue(obj, null) + "<br />"); 
} 
// Individual values  
int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null)); 
sb.Append(" Take alone five Value: " + five); 
string result = sb.ToString(); 
Response.Write(result); 

Test 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
Take the value of five alone: 11111111

Okay, now that you've learned about the use of class property reflection, you've probably figured out that you can do the same thing with methods, t.GetProperties () instead of t.GetMethods (), as above.


Related articles: