C#反射技術的簡單操作(讀取和設置類的屬性)


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,微軟已經為我們提供了足夠多的方法。

首先建立一個測試的類

 
  1. public class MyClass 
  2. public int one { setget; } 
  3. public int two { setget; } 
  4. public int five { setget; } 
  5. public int three { setget; } 
  6. public int four { setget; } 
 

然后編寫反射該類的代碼

 
  1. MyClass obj = new MyClass(); 
  2. Type t = typeof(MyClass); 
  3. //循環賦值 
  4. int i = 0; 
  5. foreach (var item in t.GetProperties()) 
  6. item.SetValue(obj, i, null); 
  7. i += 1; 
  8. //單獨賦值 
  9. t.GetProperty("five").SetValue(obj, 11111111, null); 
  10. //循環獲取 
  11. StringBuilder sb = new StringBuilder(); 
  12. foreach (var item in t.GetProperties()) 
  13. sb.Append("類型:" + item.PropertyType.FullName + " 屬性名:" + item.Name + " 值:" + item.GetValue(obj, null) + "<br />"); 
  14. //單獨取值 
  15. int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null)); 
  16. sb.Append("單獨取five的值:" + five); 
  17. string result = sb.ToString(); 
  18. 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;的引用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM