public class A { public int Property1 { get; set; } } static void Main(){ A aa = new A(); Type type = aa.GetType();//獲取類型 System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); propertyInfo.SetValue(aa, 5, null);//給對應屬性賦值 int value = (int)propertyInfo.GetValue(aa, null); Console.WriteLine(value ); }
少量屬性的自動化操作手動添加幾下當然是沒有問題的,但是屬性數量較多的時候敲起這些繁鎖的代碼可以困了,再說對擴展和維護性造成很多的不便,這時,就需要使用反射來實現了。
要想對一個類型實例的屬性或字段進行動態賦值或取值,首先得得到這個實例或類型的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);
測試顯示結果:
類型:System.Int32 屬性名:one 值:0
類型:System.Int32 屬性名:two 值:1
類型:System.Int32 屬性名:five 值:11111111
類型:System.Int32 屬性名:three 值:3
類型:System.Int32 屬性名:four 值:4
單獨取five的值:11111111
了解了類的屬性反射使用后,那么方法也是可以這樣做的,即t.GetProperties()改為t.GetMethods(),操作方法同上。
注:以上代碼中如不能直接使用請添加using System.Text;的引用。