地球人都知道 構建通用的功能 泛型和反射是必不可少的,然后現在很多人都用ORM實體框架+泛型也可以構建
但其內部也是通過反射實現的。
解開迷霧 見天日吧。
---c#代碼
public class Boy { public int BoyId { get; set; } public string BoyName { get; set; } } public class Girl { public int GirlId { get; set; } public string GirlName { get; set; } } class Program { static IDictionary<object, object> GetList<T>() where T : class { Type modelType = typeof(T); //創建T對象 T model = (T)Activator.CreateInstance(modelType); //T model = Activator.CreateInstance<T>(); Type t = model.GetType(); //獲取T對象的所有屬性 PropertyInfo[] props = t.GetProperties(); //將屬性名稱作為key,屬性值作為value Dictionary<object, object> dict = new Dictionary<object, object>(); foreach (PropertyInfo prop in props) { //獲取屬性的名稱 string propName = prop.Name; //為model對象的pro屬性設置值 //如果此屬性類型是int就賦值10 if (prop.PropertyType==typeof(Int32)) { //在實際開發中 一般用 DataRow獲取數據庫相應的字段值如 dr[propName] prop.SetValue(model, 10, null); } else //如果此屬性類型 不是 int就統一賦值"aaa" { prop.SetValue(model, "aaa", null); } //獲取model中是屬性值 object propValue=prop.GetValue(model, null); dict.Add(propName,propValue.ToString()); } return dict; } static void Main(string[] args) { foreach (var item in GetList<Boy>()) { Console.WriteLine(item.Key+":"+item.Value); } Console.WriteLine("success"); Console.ReadKey(); } }
---運行結果
---泛型約束

