為了動態(tài)地分配或賦值類型實(shí)例的屬性,我們必須首先獲取實(shí)例或類型的Type,錯新技術(shù)頻道已經(jīng)為大家整理了C#反射技術(shù)的簡單操作,希望對你學(xué)習(xí)這方面知識有幫助。
首先建立一個(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(),操作方法同上。
以上就是錯新技術(shù)頻道給大家介紹的C#反射技術(shù)的簡單操作,通過上文的了解大家都知道了嗎?如果大家還想了解更多的內(nèi)容就關(guān)注錯新技術(shù)頻道吧!