欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

类型转换一种处理方式

程序员文章站 2022-06-18 09:58:53
背景 1. 在开发中,我们会碰到诸如String类型转换为Int等等问题,虽然处理起来简单,但是本着DRY(Don't Repeat Yourself )原则,还是有必要封装处理下; 2. 具体代码: "MasterChief" 3. Nuget:Install Package MasterChie ......

背景

  1. 在开发中,我们会碰到诸如string类型转换为int等等问题,虽然处理起来简单,但是本着dry(don't repeat yourself )原则,还是有必要封装处理下;
  2. 具体代码:masterchief
  3. nuget:install-package masterchief.dotnet4.utilities
  4. 欢迎star,欢迎issues;

实现代码

using system;
using system.componentmodel;
using system.data;
using system.globalization;
 
namespace masterchief.dotnet4.utilities.common
{
    /// <summary>
    ///     转换帮助类
    /// </summary>
    public static class converthelper
    {
        #region methods
 
        /// <summary>
        ///     转换成布尔类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static bool tobooleanordefault(this object data, bool defalut = false)
        {
            return data != null && bool.tryparse(data.tostring(), out var result) ? result : defalut;
        }
 
        /// <summary>
        ///     转换成byte类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static byte tobyteordefault(this object data, byte defalut = 0x00)
        {
            return data != null && byte.tryparse(data.tostring(), out var result) ? result : defalut;
        }
 
        /// <summary>
        ///     转换为农历年
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns>农历年</returns>
        public static string tochinesedate(this datetime date)
        {
            var cndate = new chineselunisolarcalendar();
            string[] months = { string.empty, "正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月" };
            string[] days =
            {
                string.empty, "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五",
                "十六", "十七", "十八", "十九", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
            };
            string[] years =
            {
                string.empty, "甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", "辛未", "壬申", "癸酉", "甲戌", "乙亥", "丙子", "丁丑", "戊寅",
                "己卯", "庚辰", "辛己", "壬午", "癸未", "甲申", "乙酉", "丙戌", "丁亥", "戊子", "己丑", "庚寅", "辛卯", "壬辰", "癸巳", "甲午", "乙未",
                "丙申", "丁酉", "戊戌", "己亥", "庚子", "辛丑", "壬寅", "癸丑", "甲辰", "乙巳", "丙午", "丁未", "戊申", "己酉", "庚戌", "辛亥", "壬子",
                "癸丑", "甲寅", "乙卯", "丙辰", "丁巳", "戊午", "己未", "庚申", "辛酉", "壬戌", "癸亥"
            };
            var year = cndate.getyear(date);
            var yearcn = years[cndate.getsexagenaryyear(date)];
            int month = cndate.getmonth(date),
                day = cndate.getdayofmonth(date),
                leapmonth = cndate.getleapmonth(year);
            var monthcn = months[month];
 
            if (leapmonth > 0)
            {
                monthcn = month == leapmonth ? $"闰{months[month - 1]}" : monthcn;
                monthcn = month > leapmonth ? months[month - 1] : monthcn;
            }
 
            return $"{yearcn}年{monthcn}{days[day]}";
        }
 
        /// <summary>
        ///     将阿拉伯数字转换中文日期数字
        /// </summary>
        /// <param name="data">日期范围1~31</param>
        /// <returns>中文日期数字</returns>
        public static string tochineseday(int data)
        {
            string result = string.empty;
 
            if (!(data == 0 || data > 32))
            {
                string[] days =
                {
                    "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七",
                    "十八", "十九", "廿十", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十", "三十一"
                };
                result = days[data];
            }
 
            return result;
        }
 
        /// <summary>
        ///     将阿拉伯数字转换成中文月份数字
        ///     <para>eg:converthelper.tochinesemonth(1)==> "一"</para>
        /// </summary>
        /// <param name="data">月份范围1~12</param>
        /// <returns>中文月份数字</returns>
        public static string tochinesemonth(this int data)
        {
            var result = string.empty;
 
            if (!(data == 0 || data > 12))
            {
                string[] months = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };
                result = months[data];
            }
 
            return result;
        }
 
        /// <summary>
        ///     转换成日期
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>日期</returns>
        public static datetime todateordefault(this object data, datetime defalut)
        {
            return datetime.tryparse(data.tostring(), out var result) ? result : defalut;
        }
 
        /// <summary>
        ///     日期转化
        /// </summary>
        /// <returns>目标日期</returns>
        /// <param name="data">数据.</param>
        public static datetime todateordefault(this object data)
        {
            return todateordefault(data, datetime.minvalue);
        }
 
        /// <summary>
        ///     转换成decimal类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static decimal todecimalordefault(this object data, decimal defalut = 0m)
        {
            if (data != null)
            {
                var result = decimal.tryparse(data.tostring(), out var parsedecimalvalue);
                return result ? parsedecimalvalue : defalut;
            }
 
            return defalut;
        }
 
        /// <summary>
        ///     转换成double类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static double todoubleordefault(this object data, double defalut = 0d)
        {
            if (data != null)
            {
                var result = double.tryparse(data.tostring(), out var parseintvalue);
                return result ? parseintvalue : defalut;
            }
 
            return defalut;
        }
 
        /// <summary>
        ///     转换成int32类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static int toint32ordefault(this object data, int defalut = 0)
        {
            if (data != null)
            {
                var result = int.tryparse(data.tostring(), out var parseintvalue);
                return result ? parseintvalue : defalut;
            }
 
            return defalut;
        }
 
        /// <summary>
        ///     转换成int64类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static long toint64ordefault(this object data, long defalut = 0)
        {
            if (data != null)
            {
                var result = long.tryparse(data.tostring(), out var parseintvalue);
                return result ? parseintvalue : defalut;
            }
 
            return defalut;
        }
 
        /// <summary>
        ///     转换成int类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static int tointordefault(this object data, int defalut = 0)
        {
            if (data != null)
            {
                var result = int.tryparse(data.tostring(), out var parseintvalue);
                return result ? parseintvalue : defalut;
            }
 
            return defalut;
        }
 
        /// <summary>
        ///     按照列名称获取int值
        /// </summary>
        /// <param name="row">datarow</param>
        /// <param name="columnname">列名称</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>若列不等于null则返回实际值</returns>
        public static int tointordefault(this datarow row, string columnname, int defalut = 0)
        {
            if (row != null)
                if (row.isnull(columnname))
                    int.tryparse(row[columnname].tostring(), out defalut);
 
            return defalut;
        }
 
        /// <summary>
        ///     按照列索引获取int值
        /// </summary>
        /// <param name="row">datarow</param>
        /// <param name="columnindex">列索引</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>若列不等于null则返回实际值</returns>
        public static int tointordefault(this datarow row, int columnindex, int defalut = 0)
        {
            if (row != null)
                if (row.isnull(columnindex))
                    int.tryparse(row[columnindex].tostring(), out defalut);
 
            return defalut;
        }
 
        /// <summary>
        ///     转换成int16类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static short toshortordefault(this object data, short defalut)
        {
            if (data != null)
            {
                var result = short.tryparse(data.tostring(), out var parseintvalue);
                return result ? parseintvalue : defalut;
            }
 
            return defalut;
        }
 
        /// <summary>
        ///     泛型数组转换为字符串
        /// </summary>
        /// <typeparam name="t">泛型</typeparam>
        /// <param name="array">泛型数组</param>
        /// <param name="delimiter">分隔符</param>
        /// <returns>转换好的字符串</returns>
        public static string tostring<t>(this t[] array, string delimiter)
        {
            var data = array.convertall(array, n => n.tostring());
            return string.join(delimiter, data);
        }
 
        /// <summary>
        ///     字符串类型转换
        /// </summary>
        /// <typeparam name="t">目标类型</typeparam>
        /// <param name="data">需要转换的字符串</param>
        /// <returns>转换类型</returns>
        public static t tostringbase<t>(this string data)
        {
            var result = default(t);
 
            if (!string.isnullorempty(data))
            {
                var convert = typedescriptor.getconverter(typeof(t));
                result = (t)convert.convertfrom(data);
            }
 
            return result;
        }
 
        /// <summary>
        ///     转换成string类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static string tostringordefault(this object data, string defalut)
        {
            return data == null ? defalut : data.tostring();
        }
 
        /// <summary>
        ///     将时间类型转换为字符串表述
        /// </summary>
        /// <param name="data">datetime</param>
        /// <param name="formartstring">格式化字符串</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>字符串</returns>
        public static string tostringordefault(this datetime data, string formartstring, string defalut)
        {
            if (data != default) return data.tostring(formartstring);
 
            return defalut;
        }
 
        /// <summary>
        ///     按照列名称获取sting值
        /// </summary>
        /// <param name="row">datarow</param>
        /// <param name="columnname">列名称</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>若列不等于null则返回实际值</returns>
        public static string tostringordefault(this datarow row, string columnname, string defalut)
        {
            if (row != null) defalut = row.isnull(columnname) ? defalut : row[columnname].tostring();
 
            return defalut;
        }
 
        /// <summary>
        ///     按照列索引获取sting值
        /// </summary>
        /// <param name="row">datarow</param>
        /// <param name="columnindex">列索引</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>若列不等于null则返回实际值</returns>
        public static string tostringordefault(this datarow row, int columnindex, string defalut)
        {
            if (row != null) defalut = row.isnull(columnindex) ? defalut : row[columnindex].tostring().trim();
 
            return defalut;
        }
 
        /// <summary>
        ///     转换成ushort类型
        /// </summary>
        /// <param name="data">需要转换的object</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static ushort toushortordefault(this object data, ushort defalut)
        {
            if (data != null)
            {
                var result = ushort.tryparse(data.tostring(), out var parseushortvalue);
                return result ? parseushortvalue : defalut;
            }
 
            return defalut;
        }
 
        /// <summary>
        ///     将字符串转换为guid
        /// </summary>
        /// <returns>期待guid</returns>
        /// <param name="data">数值.</param>
        public static guid toguidordefault(this string data)
        {
            return toguidordefault(data, guid.empty);
        }
 
        /// <summary>
        ///     将字符串转换为guid
        /// </summary>
        /// <param name="data">需要转换的字符串</param>
        /// <param name="defalut">默认数值</param>
        /// <returns>转换返回</returns>
        public static guid toguidordefault(this string data, guid defalut)
        {
            guid result;
            if (guid.tryparse(data, out result))
                return result;
            return defalut;
        }
 
        #endregion methods
    }
}

代码使用

  1. 实现很简单,所以使用也很简单,假如您还是很懒的话,去star下,我告诉您怎么用,哈哈哈~

结语

  1. 小弟不才,大佬轻拍;