using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Web; namespace Wms.Screen.Util.Comm { public class ConverHelper { #region object 转换T类型数据 /// /// 转换 object为 T 类型 /// /// T 类型 /// object 数据 /// 默认值 /// 是否抛出异常 /// public static T ToTSource(object obj, T defVal = default(T), bool exp = false) { T result = defVal; if (obj == null) { return result; } if (obj is T) { return (T)obj; } try { Type conversionType = typeof(T); object obj2 = null; if (conversionType.Equals(typeof(Guid))) obj2 = new Guid(Convert.ToString(obj)); else obj2 = Convert.ChangeType(obj, conversionType); result = (T)obj2; } catch (Exception ex) { if (exp == true) { throw ex; } } return result; } #endregion #region 数值类型转换 #region 转换为 bool 类型 /// /// 将object转换为 bool 类型 /// /// 待转换的object /// 缺省值(转换不成功) /// 是否抛出异常(默认不抛出) /// 转换后的bool类型结果 public static bool ToBool(object obj, bool defVal = false, bool exp = false) { bool result = defVal; try { if (obj != null) result = Convert.ToBoolean(obj); } catch (Exception ex) { if (exp == true) { throw ex; } } return result; } #endregion #region 转换为 Int 数值类型 /// /// 将object转换Int 类型 /// /// 待转换的object /// 缺省值(转换不成功) /// 是否抛出异常(默认不抛出) /// 转换后的Int类型结果 public static int ToInt(object obj, int defVal = 0, bool exp = false) { int result = defVal; try { if (obj != null) result = Convert.ToInt32(obj); } catch (Exception ex) { if (exp == true) { throw ex; } } return result; } #endregion #region 转换为 Float 数值类型 /// /// 将object转换 Float 类型 /// /// 待转换的object /// 缺省值(转换不成功) /// 是否抛出异常(默认不抛出) /// 转换后的Int类型结果 public static float ToFloat(object obj, float defVal = 0, bool exp = false) { float result = defVal; try { if (obj != null) result = Convert.ToSingle(obj); } catch (Exception ex) { if (exp == true) { throw ex; } } return result; } #endregion #region 转换为 Double 数值类型 /// /// 将object转换 double 类型 /// /// 待转换的object /// 缺省值(转换不成功) /// 是否抛出异常(默认不抛出) /// 转换后的Int类型结果 public static double ToDouble(object obj, double defVal = 0, bool exp = false) { double result = defVal; try { if (obj != null) result = Convert.ToDouble(obj); } catch (Exception ex) { if (exp == true) { throw ex; } } return result; } #endregion #region 转换为 decimal 数值类型 /// /// 将对象转换 decimal 类型 /// /// 待转换的字符串 /// 缺省值(转换不成功) /// 是否抛出异常(默认不抛出) /// 转换后的decimal类型结果 public static decimal ToDecimal(object obj, decimal defVal = 0m, bool exp = false) { decimal result = defVal; try { if (obj != null) result = Convert.ToDecimal(obj); } catch (Exception ex) { if (exp == true) { throw ex; } } return result; } #endregion #endregion #region 转换为 DateTime 日期类型 /// /// 将object转换 DateTime 日期类型 /// /// 待转换的字符串 /// 缺省值(转换不成功) /// 是否抛出异常(默认不抛出) /// 转换后的DateTime类型结果 public static DateTime ToDateTime(object obj, string defVal = "1970-01-01 08:00:00", bool exp = false) { DateTime result = DateTime.Parse(defVal); try { if (obj != null) result = Convert.ToDateTime(obj); } catch (Exception ex) { if (exp == true) { throw ex; } } return result; } #endregion #region DataTable 转 IList /// /// DataTable 转换 IList /// /// model 类型 /// DataTable集合 /// List集合 public static IList ToList(DataTable dataTable) where TSource : new() { var dataList = new List(); if (dataTable == null) { return null; } //创建一个属性的列表 List prlist = new List(); //获取TResult的类型实例 反射的入口 Type t = typeof(TSource); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 Array.ForEach(t.GetProperties(), p => { if (dataTable.Columns.IndexOf(p.Name) != -1) prlist.Add(p); }); foreach (DataRow row in dataTable.Rows) { //创建TResult的实例 TSource ob = new TSource(); //找到对应的数据 并赋值 prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, ChangeType(row[p.Name], p.PropertyType), null); }); //放入到返回的集合中. dataList.Add(ob); } return dataList; } /// 将数据转化为 type 类型 /// /// 要转化的值 /// 目标类型 /// 转化为目标类型的 Object 对象 private static object ChangeType(object value, Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { NullableConverter convertor = new NullableConverter(type); return Convert.IsDBNull(value) ? null : convertor.ConvertFrom(value); } return Convert.ChangeType(Convert.IsDBNull(value) ? null : value, type); } #endregion #region Json 解析操作 (引用 Newtonsoft.Json) /// /// object 转换 Json /// /// 源数据 /// json字符串 public static string ToJson(object obj) { string json = JsonConvert.SerializeObject(obj); return json; } /// /// 解析Json字符串 生成实体对象 /// /// 对象类型 /// Json字符串 /// 实体对象 public static T JsonToObj(string json) where T : class, new() { JsonSerializer js = new JsonSerializer(); StringReader sr = new StringReader(json); object o = js.Deserialize(new JsonTextReader(sr), typeof(T)); T result = o as T; return result; } /// /// 解析Json字符串 生成实体对象集合 /// /// 对象类型 /// Json字符串 /// 实体对象集合 public static IList JsonToListObj(string json) where T : class, new() { JsonSerializer js = new JsonSerializer(); StringReader sr = new StringReader(json); object o = js.Deserialize(new JsonTextReader(sr), typeof(List)); IList result = o as List; return result; } /// /// 解析Json字符串 生成匿名对象 /// /// 匿名对象 /// Json字符串 /// 匿名对象 /// 匿名对象 public static T JsonToAnonymous(string json, T anonymousTypeObject) { T result = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject); return result; } #endregion #region 杂项转换 #region 转换为 大写金额 /// /// 将数值转换 RMB 大写金额 /// /// 待转换数值 /// 大写金额 public static string ToRMB(decimal money) { var s = money.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A"); var d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}"); var r = Regex.Replace(d, ".", m => "负元空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟万亿兆京垓秭穰"[m.Value[0] - '-'].ToString()); return r; } #endregion #region 将客户端提交的值 转换 T 对象 /// /// 将客户端提交的值 转换T对象 /// /// T 类型 /// Request.Form /// /// /// /// public static T FromToTSource(NameValueCollection frmDats) where T : class, new() { Type type = typeof(T); string[] strArray = type.FullName.Split(new char[] { '.' }); string cls = strArray[strArray.Length - 1]; PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); T local = Activator.CreateInstance(); foreach (string data in frmDats.AllKeys) { string key = frmDats[data]; if (!string.IsNullOrEmpty(key)) key = key.TrimEnd(new char[0]); foreach (PropertyInfo info in properties) { string cls_name = string.Format("", cls, info.Name); if (data.Equals(info.Name, StringComparison.CurrentCultureIgnoreCase) || data.Equals(cls_name, StringComparison.CurrentCultureIgnoreCase)) { string typeName = info.PropertyType.ToString(); if (info.PropertyType.IsGenericType) { typeName = info.PropertyType.GetGenericArguments()[0].ToString(); } object nullInternal = GetNullInternal(info.PropertyType); Type conversionType = Type.GetType(typeName, false); if (!string.IsNullOrEmpty(key)) { nullInternal = Convert.ChangeType(key, conversionType); } info.SetValue(local, nullInternal, null); } } } return local; } /// /// 获取默认值 /// /// /// private static object GetNullInternal(Type type) { if (type.IsValueType) { if (type.IsEnum) { return GetNullInternal(Enum.GetUnderlyingType(type)); } if (type.IsPrimitive) { if (type == typeof(int)) { return 0; } if (type == typeof(double)) { return 0.0; } if (type == typeof(short)) { return (short)0; } if (type == typeof(sbyte)) { return (sbyte)0; } if (type == typeof(long)) { return 0L; } if (type == typeof(byte)) { return (byte)0; } if (type == typeof(ushort)) { return (ushort)0; } if (type == typeof(uint)) { return 0; } if (type == typeof(ulong)) { return (ulong)0L; } if (type == typeof(ulong)) { return (ulong)0L; } if (type == typeof(float)) { return 0f; } if (type == typeof(bool)) { return false; } if (type == typeof(char)) { return '\0'; } } else { if (type == typeof(DateTime)) { return DateTime.MinValue; } if (type == typeof(decimal)) { return 0M; } if (type == typeof(Guid)) { return Guid.Empty; } if (type == typeof(TimeSpan)) { return new TimeSpan(0, 0, 0); } } } return null; } #endregion #endregion #region 转换字符串 /// /// 转换字符串,因为可能有空,直接转换会报错 /// /// /// /// public static string ToString(object obj, string defVal = "") { string result = defVal; if (obj == null) { return result; } return obj.ToString(); } #endregion public static List DataTableToList(DataTable dt) where T : class, new() { // 定义集合 List ts = new List(); //定义一个临时变量 string tempName = string.Empty; //遍历DataTable中所有的数据行 foreach (DataRow dr in dt.Rows) { T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); //遍历该对象的所有属性 foreach (PropertyInfo pi in propertys) { tempName = pi.Name;//将属性名称赋值给临时变量 //检查DataTable是否包含此列(列名==对象的属性名) if (dt.Columns.Contains(tempName)) { //取值 object value = dr[tempName]; //如果非空,则赋给对象的属性 if (value != DBNull.Value) { pi.SetValue(t, value, null); } } } //对象添加到泛型集合中 ts.Add(t); } return ts; } } }