此代码非原创,很早前从百度上搜索的,如有侵权,请联系我删除
public static T ConvertDic<T>(Dictionary<string, object> dic)
{
T model = Activator.CreateInstance<T>();
PropertyInfo[] modelPro = model.GetType().GetProperties();
if (modelPro.Length > 0 && dic.Count() > 0)
{
for (int i = 0; i < modelPro.Length; i++)
{
PropertyInfo proInfo = modelPro[i];
if (dic.ContainsKey(proInfo.Name))
{
object value = dic[proInfo.Name];
if (!proInfo.PropertyType.IsGenericType)
{
//非泛型
proInfo.SetValue(model, value == null ? null
: string.IsNullOrWhiteSpace(value.ToString()) ? null
: Convert.ChangeType(value, proInfo.PropertyType), null);
}
else
{
//泛型Nullable<>
Type genericTypeDefinition = proInfo.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
proInfo.SetValue(model, value == null ? null
: string.IsNullOrWhiteSpace(value.ToString()) ? null
: Convert.ChangeType(value, Nullable.GetUnderlyingType(proInfo.PropertyType)), null);
}
}
}
}
}
return model;
}