c# 通過反射獲取類中的所有字段和屬性


Reflection中文翻譯為反射,是.Net中獲取運行時類型信息的方式。Net的應用程序由幾個部分:程序集(Assembly)、模塊(Module)、類型(class)組成。 反射提供一種編程的方式,讓程序員可以在程序運行期獲得這幾個組成部分的相關信息。 Assembly類可以獲得正在運行的裝配件信息,也可以動態的加載裝配件,以及在裝配件中查找類型信息,並創建該類型的實例。Type類可以獲得對象的類型信息,此信息包含對象的所有要素:方法、構造器、屬性等等,通過Type類可以得到這些要素的信息,並且調用之。MethodInfo包含方法的信息,通過這個類可以得到方法的名稱、參數、返回值等,並且可以調用之。諸如此類,還有FieldInfo、EventInfo等等,這些類都包含在System.Reflection命名空間下。


獲取類中的屬性

1
/// <summary> 2 /// 獲取類中的屬性 3 /// </summary> 4 /// <returns>所有屬性名稱</returns> 5 public List<string> GetProperties<T>(T t) 6 { 7 List<string> ListStr = new List<string>(); 8 if (t == null) 9 { 10 return ListStr; 11 } 12 System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); 13 if (properties.Length <= 0) 14 { 15 return ListStr; 16 } 17 foreach (System.Reflection.PropertyInfo item in properties) 18 { 19 string name = item.Name; //名稱 20 object value = item.GetValue(t, null); // 21 22 if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) 23 { 24 ListStr.Add(name); 25 } 26 else 27 { 28 GetProperties(value); 29 } 30 } 31 return ListStr; 32 } 33 34

獲取類中的字段

35 
36         /// <summary>
37         /// 獲取類中的字段 38         /// </summary>
39         /// <returns>所有字段名稱</returns>
40         public List<string> GetFields<T>(T t) 41  { 42 
43             List<string> ListStr = new List<string>(); 44             if (t == null) 45  { 46                 return ListStr; 47  } 48             System.Reflection.FieldInfo[] fields = t.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); 49             if (fields.Length <= 0) 50  { 51                 return ListStr; 52  } 53             foreach (System.Reflection.FieldInfo item in fields) 54  { 55                 string name = item.Name; //名稱
56                 object value = item.GetValue(t);  //
57 
58                 if (item.FieldType.IsValueType || item.FieldType.Name.StartsWith("String")) 59  { 60  ListStr.Add(name); 61  } 62                 else
63  { 64  GetFields(value); 65  } 66  } 67             return ListStr; 68 
69 
70         }

 


免責聲明!

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



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