/// <summary>标签:反射,obj,string,val,C#,field,实例,PropertyType,null From: https://blog.51cto.com/xxjjing/5805036
/// 为指定对象分配参数
/// </summary>
/// <typeparam name="T">待赋值的类型</typeparam>
/// <param name="dic">字段/值</param>
/// <returns></returns>
private T Assign<T>(Dictionary<string, string> dic) where T : new()
{
Type t = typeof (T);
T entity = new T();
var fields = t.GetProperties();
string val = string.Empty;
object obj = null;
foreach (var field in fields)
{
if (!dic.Keys.Contains(field.Name))
continue;
val = dic[field.Name];
//非泛型
if (!field.PropertyType.IsGenericType)
obj = string.IsNullOrEmpty(val) ? null : Convert.ChangeType(val, field.PropertyType);
else //泛型Nullable<>
{
Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof (Nullable<>))
{
obj = string.IsNullOrEmpty(val)
? null
: Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
}
}
field.SetValue(entity, obj, null);
}
return entity;
}