背景#
- 在开发中,我们会碰到诸如String类型转换为Int等等问题,虽然处理起来简单,但是本着DRY(Don't Repeat Yourself )原则,还是有必要封装处理下;
- 具体代码:MasterChief
- Nuget:Install-Package MasterChief.DotNet4.Utilities
- 欢迎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> /// 将阿拉伯数字转换中文日期数字 ///