要想對一個類型實例的屬性或字段進行動態賦值或取值,首先得得到這個實例或類型的Type,微軟已經為我們提供了足夠多的方法。
首先建立一個測試的類
復制代碼 代碼如下:
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);
新聞熱點
疑難解答
圖片精選