using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Runtime.InteropServices.ComTypes; using System.Text; namespace MES.Utility.Core { /// /// 处理数据类型转换,数制转换、编码转换相关的类 /// public static class ConvertHelper { /// /// decimal保留指定位数小数 /// /// 原始数量 /// 保留小数位数 /// 截取指定小数位数后的数量字符串 public static string ToString(this decimal num, int scale) { string numToString = num.ToString(); int index = numToString.IndexOf("."); int length = numToString.Length; if (index != -1) { return string.Format("{0}.{1}", numToString.Substring(0, index), numToString.Substring(index + 1, Math.Min(length - index - 1, scale))); } else { return num.ToString(); } } /// /// 数字科学计数法处理 /// /// /// public static bool ChangeToDecimal(this string value, out Decimal dData) { try { dData = 0.0M; if (value.Contains("E") || value.Contains("e")) { dData = Convert.ToDecimal(Decimal.Parse(value.ToString(), System.Globalization.NumberStyles.Float)); } else { dData = Convert.ToDecimal(value); } return true; } catch { dData = 0.0M; return false; } } public static decimal ChangeToDecimal2(this string value) { try { decimal dData = 0.0M; if (value.Contains("E") || value.Contains("e")) { dData = Convert.ToDecimal(Decimal.Parse(value.ToString(), System.Globalization.NumberStyles.Float)); } else { dData = Convert.ToDecimal(value); } return dData; } catch { return 0.0M; } } public static DataTable ToDataTable(this List data) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable dataTable = new DataTable(); for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType); } object[] values = new object[properties.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = properties[i].GetValue(item); } dataTable.Rows.Add(values); } return dataTable; } public static List ToList(this DataTable table) { if (table == null) { return null; } List rows = new List(); foreach (DataRow row in table.Rows) { rows.Add(row); } return rows.ToList(); } public static List ToList(this List rows) { List list = null; if (rows != null) { list = new List(); foreach (DataRow row in rows) { T item = row.ToObject(); list.Add(item); } } return list; } public static T ToObject(this DataRow row) { T obj = default(T); if (row != null) { obj = Activator.CreateInstance(); foreach (DataColumn column in row.Table.Columns) { PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName); try { object value = row[column.ColumnName]; prop.SetValue(obj, value, null); } catch (Exception ex) { //You can log something here //throw; } } } return obj; } #region 各进制数间转换 /// /// 实现各进制数间的转换。ConvertBase("15",10,16)表示将十进制数15转换为16进制的数。 /// /// 要转换的值,即原值 /// 原值的进制,只能是2,8,10,16四个值。 /// 要转换到的目标进制,只能是2,8,10,16四个值。 public static string ConvertBase(string value, int from, int to) { if (!isBaseNumber(from)) throw new ArgumentException("参数from只能是2,8,10,16四个值。"); if (!isBaseNumber(to)) throw new ArgumentException("参数to只能是2,8,10,16四个值。"); int intValue = Convert.ToInt32(value, from); //先转成10进制 string result = Convert.ToString(intValue, to); //再转成目标进制 if (to == 2) { int resultLength = result.Length; //获取二进制的长度 switch (resultLength) { case 7: result = "0" + result; break; case 6: result = "00" + result; break; case 5: result = "000" + result; break; case 4: result = "0000" + result; break; case 3: result = "00000" + result; break; } } return result; } /// /// 判断是否是 2 8 10 16 /// /// /// private static bool isBaseNumber(int baseNumber) { if (baseNumber == 2 || baseNumber == 8 || baseNumber == 10 || baseNumber == 16) return true; return false; } #endregion #region 使用指定字符集将string转换成byte[] /// /// 将string转换成byte[]。 /// /// 要转换的字符串 public static byte[] StringToBytes(string text) { return Encoding.Default.GetBytes(text); } /// /// 使用指定字符集将string转换成byte[] /// /// 要转换的字符串 /// 字符编码 public static byte[] StringToBytes(string text, Encoding encoding) { return encoding.GetBytes(text); } #endregion #region 使用指定字符集将byte[]转换成string /// /// 将byte[]转换成string /// /// 要转换的字节数组 public static string BytesToString(byte[] bytes) { return Encoding.Default.GetString(bytes); } /// /// 使用指定字符集将byte[]转换成string。 /// /// 要转换的字节数组 /// 字符编码 public static string BytesToString(byte[] bytes, Encoding encoding) { return encoding.GetString(bytes); } #endregion #region string转long /// /// string转long /// public static long ToInt64(this string value) { long? val = ToNullableInt64(value); if (val == null) return 0; return val.Value; } #endregion #region string转long? /// /// string转long? /// public static long? ToNullableInt64(this string value) { long? result = null; if (!string.IsNullOrWhiteSpace(value)) { long d; if (long.TryParse(value, out d)) { result = d; } } return result; } #endregion #region 将byte[]转换成int /// /// 将byte[]转换成int /// /// 需要转换成整数的byte数组 public static int BytesToInt32(byte[] data) { //如果传入的字节数组长度小于4,则返回0 if (data.Length < 4) { return 0; } //定义要返回的整数 int num = 0; //如果传入的字节数组长度大于4,需要进行处理 if (data.Length >= 4) { //创建一个临时缓冲区 byte[] tempBuffer = new byte[4]; //将传入的字节数组的前4个字节复制到临时缓冲区 Buffer.BlockCopy(data, 0, tempBuffer, 0, 4); //将临时缓冲区的值转换成整数,并赋给num num = BitConverter.ToInt32(tempBuffer, 0); } //返回整数 return num; } #endregion #region 将数据转换为整型 #region string转int /// /// string转int /// public static int ToInt32(this string value) { int? val = ToNullableInt32(value); if (val == null) return 0; return val.Value; } #endregion #region string转int? /// /// string转int? /// public static int? ToNullableInt32(this string value) { int? result = null; if (!string.IsNullOrWhiteSpace(value)) { int d; if (int.TryParse(value, out d)) { result = d; } } return result; } #endregion /// /// 将数据转换为整型 转换失败返回默认值 /// /// 数据类型 /// 数据 /// 默认值 /// public static int ToInt32(T data, int defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToInt32(data); } catch { return defValue; } } /// /// 将数据转换为整型 转换失败返回默认值。 /// /// 数据 /// 默认值 /// public static int ToInt32(string data, int defValue) { //如果为空则返回默认值 if (string.IsNullOrEmpty(data)) { return defValue; } int temp = 0; if (Int32.TryParse(data, out temp)) { return temp; } else { return defValue; } } /// /// 将数据转换为整型 转换失败返回默认值 /// /// 数据 /// 默认值 /// public static int ToInt32(object data, int defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToInt32(data); } catch { return defValue; } } #endregion #region 将数据转换为布尔型 /// /// 将数据转换为布尔类型 转换失败返回默认值 /// /// 数据类型 /// 数据 /// 默认值 /// public static bool ToBoolean(T data, bool defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToBoolean(data); } catch { return defValue; } } /// /// 将数据转换为布尔类型 转换失败返回 默认值 /// /// 数据 /// 默认值 /// public static bool ToBoolean(string data, bool defValue) { //如果为空则返回默认值 if (string.IsNullOrEmpty(data)) { return defValue; } bool temp = false; if (bool.TryParse(data, out temp)) { return temp; } else { return defValue; } } /// /// 将数据转换为布尔类型 转换失败返回 默认值 /// /// 数据 /// 默认值 /// public static bool ToBoolean(object data, bool defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToBoolean(data); } catch { return defValue; } } #endregion #region 将数据转换为单精度浮点型 /// /// 将数据转换为单精度浮点型 转换失败 返回默认值 /// /// 数据类型 /// 数据 /// 默认值 /// public static float ToFloat(T data, float defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToSingle(data); } catch { return defValue; } } /// /// 将数据转换为单精度浮点型 转换失败返回默认值 /// /// 数据 /// 默认值 /// public static float ToFloat(object data, float defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToSingle(data); } catch { return defValue; } } /// /// 将数据转换为单精度浮点型 转换失败返回默认值 /// /// 数据 /// 默认值 /// public static float ToFloat(string data, float defValue) { //如果为空则返回默认值 if (string.IsNullOrEmpty(data)) { return defValue; } float temp = 0; if (float.TryParse(data, out temp)) { return temp; } else { return defValue; } } #endregion #region 将数据转换为双精度浮点型 #region string转double /// /// string转double /// public static double ToDouble(this string value) { double? val = ToNullableDouble(value); if (val == null) return 0; return val.Value; } #endregion #region string转double? /// /// string转double? /// public static double? ToNullableDouble(this string value) { double? result = null; if (!string.IsNullOrWhiteSpace(value)) { double d; if (double.TryParse(value, out d)) { result = d; } } return result; } #endregion /// /// 将数据转换为双精度浮点型 转换失败返回默认值 /// /// 数据的类型 /// 要转换的数据 /// 默认值 /// public static double ToDouble(T data, double defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToDouble(data); } catch { return defValue; } } /// /// 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 /// /// 数据的类型 /// 要转换的数据 /// 小数的位数 /// 默认值 /// public static double ToDouble(T data, int decimals, double defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Math.Round(Convert.ToDouble(data), decimals); } catch { return defValue; } } /// /// 将数据转换为双精度浮点型 转换失败返回默认值 /// /// 要转换的数据 /// 默认值 /// public static double ToDouble(object data, double defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToDouble(data); } catch { return defValue; } } /// /// 将数据转换为双精度浮点型 转换失败返回默认值 /// /// 要转换的数据 /// 默认值 /// public static double ToDouble(string data, double defValue) { //如果为空则返回默认值 if (string.IsNullOrEmpty(data)) { return defValue; } double temp = 0; if (double.TryParse(data, out temp)) { return temp; } else { return defValue; } } /// /// 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 /// /// 要转换的数据 /// 小数的位数 /// 默认值 /// public static double ToDouble(object data, int decimals, double defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Math.Round(Convert.ToDouble(data), decimals); } catch { return defValue; } } /// /// 将数据转换为双精度浮点型,并设置小数位 转换失败返回默认值 /// /// 要转换的数据 /// 小数的位数 /// 默认值 /// public static double ToDouble(string data, int decimals, double defValue) { //如果为空则返回默认值 if (string.IsNullOrEmpty(data)) { return defValue; } double temp = 0; if (double.TryParse(data, out temp)) { return Math.Round(temp, decimals); } else { return defValue; } } #endregion #region 将数据转换为指定类型 /// /// 将数据转换为指定类型 /// /// 转换的数据 /// 转换的目标类型 public static object ConvertTo(object data, Type targetType) { if (data == null || Convert.IsDBNull(data)) { return null; } Type type2 = data.GetType(); if (targetType == type2) { return data; } if (((targetType == typeof(Guid)) || (targetType == typeof(Guid?))) && (type2 == typeof(string))) { if (string.IsNullOrEmpty(data.ToString())) { return null; } return new Guid(data.ToString()); } if (targetType.IsEnum) { try { return Enum.Parse(targetType, data.ToString(), true); } catch { return Enum.ToObject(targetType, data); } } if (targetType.IsGenericType) { targetType = targetType.GetGenericArguments()[0]; } return Convert.ChangeType(data, targetType); } /// /// 将数据转换为指定类型 /// /// 转换的目标类型 /// 转换的数据 public static T ConvertTo(object data) { if (data == null || Convert.IsDBNull(data)) return default(T); object obj = ConvertTo(data, typeof(T)); if (obj == null) { return default(T); } return (T)obj; } #endregion #region 将数据转换Decimal #region string转decimal /// /// string转decimal /// public static decimal ToDecimal(this string value) { decimal? val = ToNullableDecimal(value); if (null == val) { return 0; } return val.Value; } #endregion #region string转decimal? /// /// string转decimal? /// public static decimal? ToNullableDecimal(this string value) { decimal? result = null; if (!string.IsNullOrWhiteSpace(value)) { decimal d; if (decimal.TryParse(value, out d)) { result = d; } } return result; } #endregion #region decimal?转decimal /// /// decimal?转decimal /// public static decimal ToDecimal(this decimal? value) { if (value != null) return value.Value; return 0; } #endregion /// /// 将数据转换为Decimal 转换失败返回默认值 /// /// 数据类型 /// 数据 /// 默认值 /// public static Decimal ToDecimal(T data, Decimal defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToDecimal(data); } catch { return defValue; } } /// /// 将数据转换为Decimal 转换失败返回 默认值 /// /// 数据 /// 默认值 /// public static Decimal ToDecimal(object data, Decimal defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToDecimal(data); } catch { return defValue; } } /// /// 将数据转换为Decimal 转换失败返回 默认值 /// /// 数据 /// 默认值 /// public static Decimal ToDecimal(string data, Decimal defValue) { //如果为空则返回默认值 if (string.IsNullOrEmpty(data)) { return defValue; } decimal temp = 0; if (decimal.TryParse(data, out temp)) { return temp; } else { return defValue; } } #endregion #region 将数据转换为DateTime /// /// string转DateTime /// public static DateTime ToDateTime(this string value) { DateTime? val = ToNullableDateTime(value); if (val == null) return DateTime.MinValue; return val.Value; } /// /// string转DateTime? /// public static DateTime? ToNullableDateTime(this string value) { DateTime? result = null; if (!string.IsNullOrWhiteSpace(value)) { DateTime dt; if (DateTime.TryParse(value, out dt)) { result = dt; } } return result; } /// /// 将数据转换为DateTime 转换失败返回默认值 /// /// 数据类型 /// 数据 /// 默认值 /// public static DateTime ToDateTime(T data, DateTime defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToDateTime(data); } catch { return defValue; } } /// /// 将数据转换为DateTime 转换失败返回 默认值 /// /// 数据 /// 默认值 /// public static DateTime ToDateTime(object data, DateTime defValue) { //如果为空则返回默认值 if (data == null || Convert.IsDBNull(data)) { return defValue; } try { return Convert.ToDateTime(data); } catch { return defValue; } } /// /// 将数据转换为DateTime 转换失败返回 默认值 /// /// 数据 /// 默认值 /// public static DateTime ToDateTime(string data, DateTime defValue) { //如果为空则返回默认值 if (string.IsNullOrEmpty(data)) { return defValue; } DateTime temp = DateTime.Now; if (DateTime.TryParse(data, out temp)) { return temp; } else { return defValue; } } #endregion #region 半角全角转换 /// /// 转全角的函数(SBC case) /// /// 任意字符串 /// 全角字符串 /// ///全角空格为12288,半角空格为32 ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 /// public static string ConvertToSBC(string input) { //半角转全角: char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 32) { c[i] = (char)12288; continue; } if (c[i] < 127) { c[i] = (char)(c[i] + 65248); } } return new string(c); } /// 转半角的函数(DBC case) /// 任意字符串 /// 半角字符串 /// ///全角空格为12288,半角空格为32 ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 /// public static string ConvertToDBC(string input) { char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 12288) { c[i] = (char)32; continue; } if (c[i] > 65280 && c[i] < 65375) c[i] = (char)(c[i] - 65248); } return new string(c); } #endregion public static long ToTimeStamp(this DateTime dateTime) { return (long)(dateTime - DateTime.Parse("1970-01-01")).TotalMilliseconds; } public static DateTime ToDateTime(this long timestamp) { return DateTime.Parse("1970-01-01").AddMilliseconds(timestamp); } #region object转string /// /// object转string /// public static string ToString(this object value) { string result = null; if (value != null) { result = value.ToString(); } return result; } #endregion #region double?转double /// /// double?转double /// public static double ToDouble(this double? value) { if (value != null) return value.Value; return 0; } #endregion #region long?转long /// /// long?转long /// public static long ToInt64(this long? value) { if (value != null) return value.Value; return 0; } #endregion #region int?转int /// /// int?转int /// public static int ToInt32(this int? value) { if (value != null) return value.Value; return 0; } #endregion } }