目前接口統一使用 [FromBody]Dictionary<string,string> req 來接收。
有時候,需要把從req字典提取多個字段賦值給 model,幾個還好,幾十個賦值就不好了。因此設計了使用泛型、反射幫助賦值。
設計不怎么通用,隨着類型的增多,這個需要繼續迭代。

public static A MapperThree<A>(Dictionary<string, string> req) { A a = Activator.CreateInstance<A>(); try { Type Typea = typeof(A); foreach (PropertyInfo propertyInfo in Typea.GetProperties()) { if (req.ContainsKey(propertyInfo.Name)) { // Type t = ap.GetType(); string proName = propertyInfo.PropertyType.Name; if (proName == "String") { propertyInfo.SetValue(a, req[propertyInfo.Name]); } else if (proName == "Int32") { propertyInfo.SetValue(a, Convert.ToInt32(req[propertyInfo.Name])); } else if (proName == "DateTime") { propertyInfo.SetValue(a, Convert.ToDateTime(req[propertyInfo.Name])); } else if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type[] typeArray = propertyInfo.PropertyType.GetGenericArguments(); Type baseType = typeArray[0]; if (baseType.Name== "Int32") { propertyInfo.SetValue(a, Convert.ToInt32(req[propertyInfo.Name])); } else if (baseType.Name == "DateTime") { propertyInfo.SetValue(a, Convert.ToDateTime(req[propertyInfo.Name])); } } else { //非int類型 and string ,datetime類型 不做處理 } } } } catch (Exception ex) { throw ex; } return a; }
在寫這個方法時,有兩個注意點
二:可空類型,拿出來的Name都是一樣的Nullable`
也就是 Nullable<System.DateTime> 與 Nullable<System.Int> 的屬性類型名字時一樣的
解決辦法: 從可空泛型參數里獲取真實類型,下面代碼,是根據實際需求設計,不具有通用性。
當然還有很多辦法可以自動賦值,例如參數做對象綁定、參數為Json字符串通過序列化、反序列化解決。各有優缺點,根據情況權衡吧。