C# 利用泛型和反射靈活接收資料
阿新 • • 發佈:2018-12-12
private void button1_Click(object sender, EventArgs e) { //dic是獲取到的資料列表,這裡假設成有這三種 Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("UserId",1); dic.Add("Username", "zty"); dic.Add("Password", "123456"); dic.Add("Phone", "18888888888"); dic.Add("Address", "BeiJing"); //User是實體類,用來接收資料 User user = ConvertDic<User>(dic); Console.WriteLine("UserID:" + user.UserId + "\nUsername:" + user.Username + "\nPassword:" + user.Password); } public static T ConvertDic<T>(Dictionary<string,object> dic) { T model = Activator.CreateInstance<T>(); //泛型的初始化 PropertyInfo[] modelPro = model.GetType().GetProperties(); //獲取型別T中所有的屬性欄位 if( modelPro.Length > 0 && dic.Count > 0 ) { for (int i = 0; i < modelPro.Length; i++) { if(dic.ContainsKey(modelPro[i].Name)) //判斷dic中Key是否和實體類中的屬性名相同,相同則儲存。也就是想要什麼資料定義什麼有屬性的實體類 { modelPro[i].SetValue(model, dic[modelPro[i].Name], null); } } } return model; }