C#反射技術(shù)的簡單操作(讀取和設(shè)置類的屬性)
更新時(shí)間:2011年01月02日 00:47:41 作者:
反射的作用想必大家都知道了吧,少量屬性的自動(dòng)化操作手動(dòng)添加幾下當(dāng)然是沒有問題的,但是屬性數(shù)量較多的時(shí)候敲起這些繁鎖的代碼可以困了,再說對擴(kuò)展和維護(hù)性造成很多的不遍,以下代碼中如不能直接使用請?zhí)砑觰sing System.Text;的引用。
要想對一個(gè)類型實(shí)例的屬性或字段進(jìn)行動(dòng)態(tài)賦值或取值,首先得得到這個(gè)實(shí)例或類型的Type,微軟已經(jīng)為我們提供了足夠多的方法。
首先建立一個(gè)測試的類
復(fù)制代碼 代碼如下:
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; }
}
然后編寫反射該類的代碼
復(fù)制代碼 代碼如下:
MyClass obj = new MyClass();
Type t = typeof(MyClass);
//循環(huán)賦值
int i = 0;
foreach (var item in t.GetProperties())
{
item.SetValue(obj, i, null);
i += 1;
}
//單獨(dú)賦值
t.GetProperty("five").SetValue(obj, 11111111, null);
//循環(huán)獲取
StringBuilder sb = new StringBuilder();
foreach (var item in t.GetProperties())
{
sb.Append("類型:" + item.PropertyType.FullName + " 屬性名:" + item.Name + " 值:" + item.GetValue(obj, null) + "<br />");
}
//單獨(dú)取值
int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null));
sb.Append("單獨(dú)取five的值:" + five);
string result = sb.ToString();
Response.Write(result);
測試顯示結(jié)果:
類型:System.Int32 屬性名:one 值:0
類型:System.Int32 屬性名:two 值:1
類型:System.Int32 屬性名:five 值:11111111
類型:System.Int32 屬性名:three 值:3
類型:System.Int32 屬性名:four 值:4
單獨(dú)取five的值:11111111
好了,了解了類的屬性反射使用后,聰明的你可能就想到了方法也是可以這樣做的,即t.GetProperties()改為t.GetMethods(),操作方法同上。
相關(guān)文章
Asp.NetCore3.1開源項(xiàng)目升級為.Net6.0的方法實(shí)現(xiàn)
自從.Net6.0出來后,一直想之前開發(fā)的項(xiàng)目升級.Net6.0,本文就詳細(xì)的介紹一下如何將Asp.NetCore3.1開源項(xiàng)目升級為.Net6.0,感興趣的小伙伴們可以參考一下2021-12-12Asp.net動(dòng)態(tài)生成html頁面的方法分享
這篇文章介紹了Asp.net動(dòng)態(tài)生成html頁面的方法,有需要的朋友可以參考一下2013-10-10jQuery Data Linking 對象與對象之間屬性的關(guān)聯(lián)
ASP.NET團(tuán)隊(duì)最近還向jQuery社區(qū)提交了被稱為data linking的技術(shù),Data Linking可以幫助你實(shí)現(xiàn)對象與對象之間屬性的關(guān)聯(lián)——當(dāng)其中一方發(fā)生改變時(shí)另一方也隨之改變。2010-12-12c#將Excel數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫的實(shí)現(xiàn)代碼
這篇文章主要介紹了c#將Excel數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫的實(shí)現(xiàn)代碼,有需要的朋友可以參考一下2013-12-12