C# 利用反射动态将字符串转换成属性对应的类型值
/// <summary> /// 为指定对象分配参数 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="dic">字段/值</param> /// <returns></returns> public static T Assign<T>(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; }