///
/// 为指定对象分配参数
///
/// 对象类型
/// 字段/值
///
public static T Assign(Dictionary<string, string> dic) where T : new()
{
Type myType = typeof(T);
T entity = new T();
var fields = myType.GetProperties();
string val = string.Empty;
object obj = null;
foreach (var field in fields)
{
if (!dic.Keys.Contains(field.Name))
continue;
val = dic[field.Name];
object defaultVal;
if (field.PropertyType.Name.Equals("String"))
defaultVal = "";
else if (field.PropertyType.Name.Equals("Boolean"))
{
defaultVal = false;
val = (val.Equals("1") || val.Equals("on")).ToString();
}
else if (field.PropertyType.Name.Equals("Decimal"))
defaultVal = 0M;
else
defaultVal = 0;
if (!field.PropertyType.IsGenericType)
obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, field.PropertyType);
else
{
Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
}
field.SetValue(entity, obj, null);
}
return entity;
}
本文介绍了一种将字典类型数据转换为特定对象类型的实用方法,通过反射机制,该方法能够智能地为对象属性赋值,支持字符串、布尔值、十进制数等多种数据类型,同时兼容可空类型。

768

被折叠的 条评论
为什么被折叠?



