【转】c# 类反射简单操作

转:http://www.jb51.net/article/25863.htm

首先建立一个测试的类 

复制代码代码如下:

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; } 


然后编写反射该类的代码 

复制代码代码如下:

MyClass obj = new MyClass(); 
Type t = typeof(MyClass); 
//循环赋值 
int i = 0; 
foreach (var item in t.GetProperties()) 

item.SetValue(obj, i, null); 
i += 1; 

//单独赋值 
t.GetProperty("five").SetValue(obj, 11111111, null); 
//循环获取 
StringBuilder sb = new StringBuilder(); 
foreach (var item in t.GetProperties()) 

sb.Append("类型:" + item.PropertyType.FullName + " 属性名:" + item.Name + " 值:" + item.GetValue(obj, null) + "<br />"); 

//单独取值 
int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null)); 
sb.Append("单独取five的值:" + five); 
string result = sb.ToString(); 
Response.Write(result); 


测试显示结果: 
类型:System.Int32 属性名:one 值:0 
类型:System.Int32 属性名:two 值:1 
类型:System.Int32 属性名:five 值:11111111 
类型:System.Int32 属性名:three 值:3 
类型:System.Int32 属性名:four 值:4 
单独取five的值:11111111 

原文地址:https://www.cnblogs.com/wdw31210/p/4088998.html