目前接口统一使用 [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[];
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字符串通过序列化、反序列化解决。各有优缺点,根据情况权衡吧。