|
记录下在开发中经常用到的类型转换- /// <summary>
- /// 转换扩展类
- /// </summary>
- public static partial class Extensions
- {
- #region 转换为long
- /// <summary>
- /// 将object转换为long,若转换失败,则返回0。不抛出异常。
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static long ParseToLong(this object obj)
- {
- try
- {
- return long.Parse(obj.ToString() ?? string.Empty);
- }
- catch
- {
- return 0L;
- }
- }
- /// <summary>
- /// 将object转换为long,若转换失败,则返回指定值。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- public static long ParseToLong(this string str, long defaultValue)
- {
- try
- {
- return long.Parse(str);
- }
- catch
- {
- return defaultValue;
- }
- }
- #endregion
- #region 转换为int
- /// <summary>
- /// 将object转换为int,若转换失败,则返回0。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static int ParseToInt(this object str)
- {
- try
- {
- return Convert.ToInt32(str);
- }
- catch
- {
- return 0;
- }
- }
- /// <summary>
- /// 将object转换为int,若转换失败,则返回指定值。不抛出异常。
- /// null返回默认值
- /// </summary>
- /// <param name="str"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- public static int ParseToInt(this object str, int defaultValue)
- {
- if (str == null)
- {
- return defaultValue;
- }
- try
- {
- return Convert.ToInt32(str);
- }
- catch
- {
- return defaultValue;
- }
- }
- #endregion
- #region 转换为short
- /// <summary>
- /// 将object转换为short,若转换失败,则返回0。不抛出异常。
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static short ParseToShort(this object obj)
- {
- try
- {
- return short.Parse(obj.ToString() ?? string.Empty);
- }
- catch
- {
- return 0;
- }
- }
- /// <summary>
- /// 将object转换为short,若转换失败,则返回指定值。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- public static short ParseToShort(this object str, short defaultValue)
- {
- try
- {
- return short.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return defaultValue;
- }
- }
- #endregion
- #region 转换为demical
- /// <summary>
- /// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- public static decimal ParseToDecimal(this object str, decimal defaultValue)
- {
- try
- {
- return decimal.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return defaultValue;
- }
- }
- /// <summary>
- /// 将object转换为demical,若转换失败,则返回0。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static decimal ParseToDecimal(this object str)
- {
- try
- {
- return decimal.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return 0;
- }
- }
- #endregion
- #region 转化为bool
- /// <summary>
- /// 将object转换为bool,若转换失败,则返回false。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static bool ParseToBool(this object str)
- {
- try
- {
- return bool.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <param name="result"></param>
- /// <returns></returns>
- public static bool ParseToBool(this object str, bool result)
- {
- try
- {
- return bool.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return result;
- }
- }
- #endregion
- #region 转换为float
- /// <summary>
- /// 将object转换为float,若转换失败,则返回0。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static float ParseToFloat(this object str)
- {
- try
- {
- return float.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return 0;
- }
- }
- /// <summary>
- /// 将object转换为float,若转换失败,则返回指定值。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <param name="result"></param>
- /// <returns></returns>
- public static float ParseToFloat(this object str, float result)
- {
- try
- {
- return float.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return result;
- }
- }
- #endregion
- #region 转换为Guid
- /// <summary>
- /// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static Guid ParseToGuid(this string str)
- {
- try
- {
- return new Guid(str);
- }
- catch
- {
- return Guid.Empty;
- }
- }
- #endregion
- #region 转换为string
- /// <summary>
- /// 将object转换为string,若转换失败,则返回""。不抛出异常。
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string ParseToString(this object obj)
- {
- try
- {
- return obj == null ? string.Empty : obj.ToString();
- }
- catch
- {
- return string.Empty;
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string ParseToStrings<T>(this object obj)
- {
- try
- {
- if (obj is IEnumerable<T> list)
- {
- return string.Join(",", list);
- }
- return obj.ToString();
- }
- catch
- {
- return string.Empty;
- }
- }
- #endregion
- #region 转换为double
- /// <summary>
- /// 将object转换为double,若转换失败,则返回0。不抛出异常。
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static double ParseToDouble(this object obj)
- {
- try
- {
- return double.Parse(obj.ToString() ?? string.Empty);
- }
- catch
- {
- return 0;
- }
- }
- /// <summary>
- /// 将object转换为double,若转换失败,则返回指定值。不抛出异常。
- /// </summary>
- /// <param name="str"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- public static double ParseToDouble(this object str, double defaultValue)
- {
- try
- {
- return double.Parse(str.ToString() ?? string.Empty);
- }
- catch
- {
- return defaultValue;
- }
- }
- #endregion
- #region 强制转换类型
- /// <summary>
- /// 强制转换类型
- /// </summary>
- /// <typeparam name="TResult"></typeparam>
- /// <param name="source"></param>
- /// <returns></returns>
- public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
- {
- return from object item in source select (TResult)Convert.ChangeType(item, typeof(TResult));
- }
- #endregion
- #region 转换为ToUnixTime
- public static long ParseToUnixTime(this DateTime nowTime)
- {
- var startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
- return (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
- }
- #endregion
- #region List转DataTable
- /// <summary>
- /// List转DataTable
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="list"></param>
- /// <returns></returns>
- public static DataTable ListToDataTable<T>(IEnumerable<T> list)
- {
- //创建属性的集合
- List<PropertyInfo> pList = new List<PropertyInfo>();
- //获得反射的入口
- Type type = typeof(T);
- DataTable dt = new DataTable();
- //把所有的public属性加入到集合 并添加DataTable的列
- Array.ForEach<PropertyInfo>(type.GetProperties(), p =>
- {
- pList.Add(p);
- var theType = p.PropertyType;
- //处理可空类型
- if (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
- {
- dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(theType));
- }
- else
- {
- dt.Columns.Add(p.Name, theType);
- }
- });
- foreach (var item in list)
- {
- //创建一个DataRow实例
- DataRow row = dt.NewRow();
- //给row 赋值
- pList.ForEach(p =>
- {
- var v = p.GetValue(item, null);
- row[p.Name] = v == null ? DBNull.Value : v;
- });
- //加入到DataTable
- dt.Rows.Add(row);
- }
- return dt;
- }
- /// <summary>
- /// List转DataTable
- /// </summary>
- /// <param name="list"></param>
- /// <returns></returns>
- public static DataTable ListToDataTableNew(List<dynamic> list)
- {
- Dictionary<string, string> dic = new Dictionary<string, string>();
- DataTable dt = new DataTable();
- if (list != null && list.Count > 0)
- {
- foreach (var item in list[0])
- {
- string text = item.ToString();
- string key = text.Substring(1, text.IndexOf(',') - 1);
- string value = text.Substring(text.IndexOf(',') + 1, text.Length - text.IndexOf(',') - 2);
- dt.Columns.Add(key);
- }
- }
- foreach (var vlist in list)
- {
- DataRow row = dt.NewRow();
- foreach (var item in vlist)
- {
- string text = item.ToString();
- string key = text.Substring(1, text.IndexOf(',') - 1);
- string value = text.Substring(text.IndexOf(',') + 1, text.Length - text.IndexOf(',') - 2);
- //创建一个DataRow实例
- row[key] = value;
- }
- //加入到DataTable
- dt.Rows.Add(row);
- }
- return dt;
- }
- #endregion
- #region 处理Excel单元格特殊字符
- /// <summary>
- /// 处理Excel单元格特殊字符
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string ExcelCellHandle(string str)
- {
- return ToSBC(str.Replace("\n", string.Empty).Replace("_", string.Empty).Replace(" ", string.Empty).Replace("'", string.Empty));
- }
- /// <summary>
- /// 转化为半角字符串(扩展方法)
- /// </summary>
- /// <param name="input">要转化的字符串</param>
- /// <returns>半角字符串</returns>
- public static string ToSBC(string input)//single byte charactor
- {
- char[] c = input.ToCharArray();
- for (int i = 0; i < c.Length; i++)
- {
- if (c[i] == 12288)//全角空格为12288,半角空格为32
- {
- c[i] = (char)32;
- continue;
- }
- if (c[i] > 65280 && c[i] < 65375)//其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
- c[i] = (char)(c[i] - 65248);
- }
- return new string(c);
- }
- #endregion
- #region 删除最后一个字符之后的字符
- /// <summary>
- /// 删除最后结尾的一个逗号
- /// </summary>
- public static string DelLastComma(string str)
- {
- return str.Substring(0, str.LastIndexOf(","));
- }
- /// <summary>
- /// 删除最后结尾的指定字符后的字符
- /// </summary>
- public static string DelLastChar(string str, string strchar)
- {
- return str.Substring(0, str.LastIndexOf(strchar));
- }
- /// <summary>
- /// 删除最后结尾的长度
- /// </summary>
- /// <param name="str"></param>
- /// <param name="Length"></param>
- /// <returns></returns>
- public static string DelLastLength(string str, int Length)
- {
- if (string.IsNullOrEmpty(str))
- return "";
- str = str.Substring(0, str.Length - Length);
- return str;
- }
- #endregion
- }
复制代码
来源:https://www.cnblogs.com/caojiming/archive/2023/10/16/17767080.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
|