ConvertHelper
public class ConvertHelper { /// <summary> /// 转换类型 /// </summary> /// <typeparam name="T">要转换的类型,可以为Nullable的泛型</typeparam> /// <param name="val">要转换的值</param> /// <returns></returns> public static T ConvertType<T>(object val) { return ConvertType<T>(val, default(T)); } /// <summary> /// 转换类型 /// </summary> /// <typeparam name="T">要转换的类型,可以为Nullable的泛型</typeparam> /// <param name="val">要转换的值</param> /// <param name="defaultVal">转换失败默认的值</param> /// <returns></returns> public static T ConvertType<T>(object val, T defaultVal) { object returnVal = ConvertByType(val, typeof(T)); if (returnVal == null) return defaultVal; else { return (T)returnVal; } } /// <summary> /// 通过反射获取未知类型时的类型转换 /// 转换失败返回null /// </summary> /// <param name="val"></param> /// <param name="tp"></param> /// <returns></returns> public static object ConvertByType(object val, Type tp) { if (val == null) return null; if (tp.IsGenericType) { tp = tp.GetGenericArguments()[]; } #region 单独转换Datetime和String if (tp.Name.ToLower() == "datetime") { DateTime? dt = ParseDateTime(val.ToString()); if (dt == null) return null; object objDt = dt.Value; return objDt; } if (tp.Name.ToLower() == "string") { object objStr = val.ToString(); return objStr; } #endregion var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new Type[] { typeof(string), tp.MakeByRefType() }, ) }); var parameters = new object[] { val.ToString(), Activator.CreateInstance(tp) }; bool success = (bool)TryParse.Invoke(null, parameters); if (success) { ]; } return null; } /// <summary> /// 转换类型,返回是否转换成功 /// </summary> /// <typeparam name="T">要转换的类型</typeparam> /// <param name="val">要转换的值</param> /// <param name="returnVal">返回的值</param> /// <returns></returns> public static bool TryConvert<T>(object val, out T returnVal) { returnVal = default(T); if (val == null) return false; Type tp = typeof(T); if (tp.IsGenericType) { tp = tp.GetGenericArguments()[]; } #region 单独转换Datetime和string if (tp.Name.ToLower() == "datetime") { DateTime? dt = ParseDateTime(val.ToString()); if (dt == null) return false; object objDt = dt.Value; returnVal = (T)objDt; return true; } if (tp.Name.ToLower() == "string") { object objStr = val.ToString(); returnVal = (T)objStr; return true; } #endregion var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new Type[] { typeof(string), tp.MakeByRefType() }, ) }); var parameters = new object[] { val.ToString(), Activator.CreateInstance(tp) }; bool success = (bool)TryParse.Invoke(null, parameters); if (success) { returnVal = (T)parameters[]; return true; } return false; } /// <summary> /// 转换为DateTime /// </summary> /// <param name="obj"></param> /// <param name="defaultValue">返回的默认值</param> /// <returns></returns> public static DateTime ConvertToDateTime(object obj, DateTime defaultValue) { DateTime result = defaultValue; if (obj != null) { if (!DateTime.TryParse(obj.ToString().Trim(), out result)) { result = defaultValue; } } return result; } /// <summary> /// 转换成中文的星期 /// </summary> /// <param name="dt">日期</param> /// <returns>返回星期</returns> public static string ConvertToZhWeek(DateTime dt) { string week = string.Empty; switch (dt.DayOfWeek.ToString()) { case "Monday": week = "星期一"; break; case "Tuesday": week = "星期二"; break; case "Wednesday": week = "星期三"; break; case "Thursday": week = "星期四"; break; case "Friday": week = "星期五"; break; case "Saturday": week = "星期六"; break; case "Sunday": week = "星期日"; break; } return week; } /// <summary> /// 根据数据日期类型 转化日期 /// </summary> /// <param name="obj"></param> /// <param name="defaultValue"></param> /// <param name="dateFormat">输入日期格式 比如 yyyyMMdd</param> /// <returns></returns> public static DateTime ConvertToDateTime(object obj, DateTime defaultValue, string dateFormat) { DateTime result = defaultValue; if (obj != null) { //日期验证 IFormatProvider ifp = new CultureInfo("zh-TW", true); DateTime.TryParseExact(obj.ToString(), dateFormat, ifp, DateTimeStyles.None, out result); } return result; } public static decimal ToDecimal(object obj) { decimal i = 0M; try { i = Convert.ToDecimal(obj); return i; } catch (Exception) { return 0.00M; } } /// <summary> /// 获取最终字符串(排除DBNull,null,string.Empty 或空值后的真实值) /// 注:如果为DBNull,null,string.Empty 或空值,则返回string.Empty /// </summary> /// <param name="objString"></param> /// <returns></returns> public static string FinalString(object objString) { if (!ValidatHelper.IsDBNullOrNullOrEmptyString(objString)) return objString.ToString(); else return string.Empty; } /// <summary> /// 获取最终字符串(排除null,string.Empty 或空值后的真实值) /// 注:如果为DBNull,null,string.Empty 或空值,则返回string.Empty /// </summary> /// <param name="objString"></param> /// <returns></returns> public static string FinalString(string objString) { if (!ValidatHelper.IsNullOrEmptyString(objString)) return objString; else return string.Empty; } /// <summary> /// 转换为int类型 /// </summary> /// <param name="obj"></param> /// <param name="defaultValue">返回的默认值</param> /// <param name="numStyle">数字格式</param> /// <returns></returns> public static int ConvertToInt(object obj, int defaultValue, NumberStyles numStyle) { int result = defaultValue; if (obj != null && obj != DBNull.Value) { if (!int.TryParse(obj.ToString().Trim(), numStyle, null, out result)) { result = defaultValue; } } return result; } /// <summary> /// 转换为int类型 /// </summary> /// <param name="obj"></param> /// <param name="defaultValue">返回的默认值</param> /// <param name="numStyle">数字格式</param> /// <returns></returns> public static byte ConvertToByte(object obj, byte defaultValue, NumberStyles numStyle) { Byte result = defaultValue; if (obj != null && obj != DBNull.Value) { if (!Byte.TryParse(obj.ToString().Trim(), numStyle, null, out result)) { result = defaultValue; } } return result; } /// <summary> /// 转换为int类型 /// </summary> /// <param name="obj"></param> /// <param name="defaultValue">返回的默认值</param> /// <returns></returns> public static int ConvertToInt(object obj, int defaultValue) { return ConvertToInt(obj, defaultValue, NumberStyles.Number); } /// <summary> /// 转换为int类型 /// </summary> /// <param name="obj"></param> /// <param name="defaultValue">返回的默认值</param> /// <returns></returns> public static byte ConvertToByte(object obj, Byte defaultValue) { return ConvertToByte(obj, defaultValue, NumberStyles.Number); } /// <summary> /// 转换为decimal类型 /// </summary> /// <param name="obj"></param> /// <param name="defaultValue">返回的默认值</param> /// <returns></returns> public static decimal ConvertToDecimal(object obj, decimal defaultValue) { decimal result = defaultValue; if (obj != null && obj != DBNull.Value) { if (!decimal.TryParse(obj.ToString().Trim(), out result)) { result = defaultValue; } } return result; } /// <summary> /// 转换为decimal类型 /// </summary> /// <param name="obj"></param> /// <param name="defaultValue">返回的默认值</param> /// <returns></returns> public static double ConvertToDouble(object obj, double defaultValue) { double result = defaultValue; if (obj != null && obj != DBNull.Value) { if (!double.TryParse(obj.ToString().Trim(), out result)) { result = 0d; } } return result; } /// <summary> /// 将日期和时间的指定字符串表示形式转换为其等效的System.DateTime。 /// </summary> /// <param name="strDateTime">日期和时间的指定字符串表示形式</param> /// <returns>日期时间</returns> public static DateTime? ParseDateTime(string strDateTime) { DateTime retDateTime; if (!String.IsNullOrEmpty(strDateTime)) strDateTime = strDateTime.Trim(); if (string.IsNullOrEmpty(strDateTime)) return null; if (!DateTime.TryParse(strDateTime, out retDateTime)) { CultureInfo zhCN = new CultureInfo("zh-CN"); string[] formats = { "yyyyMMdd", "yyyyMMddHH", "yyyyMMddHHmm", "yyyyMMddHHmmss" }; if (!DateTime.TryParseExact(strDateTime, formats, zhCN, DateTimeStyles.None, out retDateTime)) { return null; } } return retDateTime; } /// <summary> /// 转换日期格式为yyyy-MM-dd /// </summary> /// <param name="date">要转换的日期(yyyyMMdd)</param> /// <returns></returns> public static DateTime ConverDate(string date) { if (System.Text.RegularExpressions.Regex.IsMatch(date, @"^\d{8}$")) { StringBuilder stbDate = new StringBuilder(); stbDate.Append(date.Substring(, ) + "-"); stbDate.Append(date.Substring(, ) + "-"); stbDate.Append(date.Substring(, )); if (ValidatHelper.IsStringDate(stbDate.ToString())) { return Convert.ToDateTime(stbDate.ToString()); } else { throw new Exception("日期必须是数字"); } } else { throw new Exception("日期必须是数字"); } } }
EnumHelper
public class EnumHelper { /// <summary> /// 转换如:"enum1,enum2,enum3"字符串到枚举值 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <param name="obj">枚举字符串</param> /// <returns></returns> public static T Parse<T>(string obj) { if (string.IsNullOrEmpty(obj)) return default(T); else return (T)Enum.Parse(typeof(T), obj); } public static T TryParse<T>(string obj, T defT = default(T)) { try { return Parse<T>(obj); } catch { return defT; } } public static readonly string ENUM_TITLE_SEPARATOR = ","; /// <summary> /// 根据枚举值,返回描述字符串 /// 如果多选枚举,返回以","分割的字符串 /// </summary> /// <param name="e"></param> /// <returns></returns> public static string GetEnumTitle(Enum e, Enum language = null) { if (e == null) { return ""; } string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries); Type type = e.GetType(); string ret = ""; foreach (string enumValue in valueArray) { System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim()); if (fi == null) continue; EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; && attrs[].IsDisplay) { ret += attrs[].Title + ENUM_TITLE_SEPARATOR; } } return ret.TrimEnd(ENUM_TITLE_SEPARATOR.ToArray()); } /// <summary> /// 根据枚举值,返回描述字符串 /// 如果多选枚举,返回以","分割的字符串 /// </summary> /// <param name="e"></param> /// <returns></returns> public static string GetAllEnumTitle(Enum e, Enum language = null) { if (e == null) { return ""; } string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries); Type type = e.GetType(); string ret = ""; foreach (string enumValue in valueArray) { System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim()); if (fi == null) continue; EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; ) { ret += attrs[].Title + ENUM_TITLE_SEPARATOR; } } return ret.TrimEnd(ENUM_TITLE_SEPARATOR.ToArray()); } public static EnumTitleAttribute GetEnumTitleAttribute(Enum e, Enum language = null) { if (e == null) { return null; } string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries); Type type = e.GetType(); EnumTitleAttribute ret = null; foreach (string enumValue in valueArray) { System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim()); if (fi == null) continue; EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; ) { ret = attrs[]; break; } } return ret; } public static string GetDayOfWeekTitle(DayOfWeek day, Enum language = null) { switch (day) { case DayOfWeek.Monday: return "周一"; case DayOfWeek.Tuesday: return "周二"; case DayOfWeek.Wednesday: return "周三"; case DayOfWeek.Thursday: return "周四"; case DayOfWeek.Friday: return "周五"; case DayOfWeek.Saturday: return "周六"; case DayOfWeek.Sunday: return "周日"; default: return ""; } } /// <summary> /// 返回键值对,建为枚举的EnumTitle中指定的名称和近义词名称,值为枚举项 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <param name="language"></param> /// <returns></returns> public static Dictionary<string, T> GetTitleAndSynonyms<T>(Enum language = null) where T : struct { Dictionary<string, T> ret = new Dictionary<string, T>(); //枚举值 Array arrEnumValue = typeof(T).GetEnumValues(); foreach (object enumValue in arrEnumValue) { System.Reflection.FieldInfo fi = typeof(T).GetField(enumValue.ToString()); if (fi == null) { continue; } EnumTitleAttribute[] arrEnumTitleAttr = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[]; || !arrEnumTitleAttr[].IsDisplay) { continue; } ].Title)) { ret.Add(arrEnumTitleAttr[].Title, (T)enumValue); } ].Synonyms == ].Synonyms.Length < ) { continue; } ].Synonyms) { if (!ret.ContainsKey(s)) { ret.Add(s, (T)enumValue); } } }//using return ret; } /// <summary> /// 根据枚举获取包含所有所有值和描述的哈希表,其文本是由应用在枚举值上的EnumTitleAttribute设定 /// </summary> /// <returns></returns> public static Dictionary<T, string> GetItemListByAttr<T>(Enum language = null) where T : struct { return GetItemValueListByAttr<T, T>(false, language); } public static Dictionary<T, string> GetItemList<T>(Enum language = null) where T : struct { return GetItemValueList<T, T>(false, language); } /// <summary> /// 根据枚举获取包含所有所有值和描述的哈希表,其文本是由应用在枚举值上的EnumTitleAttribute设定 /// </summary> /// <returns></returns> public static Dictionary<T, string> GetAllItemList<T>(Enum language = null) where T : struct { return GetItemValueListByAttr<T, T>(true, language); } /// <summary> /// 获取枚举所有项的标题,其文本是由应用在枚举值上的EnumTitleAttribute设定 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <param name="language">语言</param> /// <returns></returns> public static Dictionary<int, string> GetItemValueListByAttr<T>(Enum language = null) where T : struct { return GetItemValueListByAttr<T, int>(false, language); } /// <summary> /// 获取枚举所有项的标题,其文本是由应用在枚举值上的EnumTitleAttribute设定 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <param name="isAll">是否生成“全部”项</param> /// <param name="language">语言</param> /// <returns></returns> public static Dictionary<TKey, string> GetItemValueListByAttr<T, TKey>(bool isAll, Enum language = null) where T : struct { if (!typeof(T).IsEnum) { throw new Exception("参数必须是枚举!"); } Dictionary<TKey, string> ret = new Dictionary<TKey, string>(); var titles = EnumHelper.GetItemAttributeList<T>().OrderBy(t => t.Value.Order); foreach (var t in titles) { if (!isAll && (!t.Value.IsDisplay || t.Key.ToString() == "None")) continue; if (t.Key.ToString() == "None" && isAll) { ret.Add((TKey)(object)t.Key, "全部"); } else { if (!string.IsNullOrEmpty(t.Value.Title)) ret.Add((TKey)(object)t.Key, t.Value.Title); } } return ret; } /// <summary> /// 获取枚举所有项的标题 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="isAll"></param> /// <param name="language"></param> /// <returns></returns> public static Dictionary<TKey, string> GetItemValueList<T, TKey>(bool isAll, Enum language = null) where T : struct { if (!typeof(T).IsEnum) { throw new Exception("参数必须是枚举!"); } Dictionary<TKey, string> ret = new Dictionary<TKey, string>(); var titles = typeof(T).GetEnumValues(); foreach (var t in titles) { ret.Add((TKey)t, t.ToString()); } return ret; } public static List<T> GetItemKeyList<T>(Enum language = null) where T : struct { List<T> list = new List<T>(); Array array = typeof(T).GetEnumValues(); foreach (object t in array) { list.Add((T)t); } return list; } public static Dictionary<T, EnumTitleAttribute> GetItemAttributeList<T>(Enum language = null) where T : struct { if (!typeof(T).IsEnum) { throw new Exception("参数必须是枚举!"); } Dictionary<T, EnumTitleAttribute> ret = new Dictionary<T, EnumTitleAttribute>(); Array array = typeof(T).GetEnumValues(); foreach (object t in array) { EnumTitleAttribute att = GetEnumTitleAttribute(t as Enum, language); if (att != null) ret.Add((T)t, att); } return ret; } /// <summary> /// 获取枚举所有项的标题,其文本是由应用在枚举值上的EnumTitleAttribute设定 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <param name="isAll">是否生成“全部”项</param> /// <param name="language">语言</param> /// <returns></returns> public static Dictionary<TKey, string> GetAllItemValueListByAttr<T, TKey>(Enum language = null) where T : struct { return GetItemValueListByAttr<T, TKey>(true, language); } /// <summary> /// 获取一个枚举的键值对形式 /// </summary> /// <typeparam name="TEnum">枚举类型</typeparam> /// <param name="exceptTypes">排除的枚举</param> /// <returns></returns> public static Dictionary<int, string> GetEnumDictionaryByAttr<TEnum>(IEnumerable<TEnum> exceptTypes = null) where TEnum : struct { var dic = GetItemListByAttr<TEnum>(); Dictionary<int, string> dicNew = new Dictionary<int, string>(); foreach (var d in dic) { if (exceptTypes != null && exceptTypes.Contains(d.Key)) { continue; } dicNew.Add(d.Key.GetHashCode(), d.Value); } return dicNew; } public static Dictionary<int, string> GetEnumDictionary<TEnum>(IEnumerable<TEnum> exceptTypes = null) where TEnum : struct { var dic = GetItemList<TEnum>(); Dictionary<int, string> dicNew = new Dictionary<int, string>(); foreach (var d in dic) { if (exceptTypes != null && exceptTypes.Contains(d.Key)) { continue; } dicNew.Add(d.Key.GetHashCode(), d.Value); } return dicNew; } } public class EnumTitleAttribute : Attribute { private bool _IsDisplay = true; public EnumTitleAttribute(string title, params string[] synonyms) { Title = title; Synonyms = synonyms; Order = int.MaxValue; } public bool IsDisplay { get { return _IsDisplay; } set { _IsDisplay = value; } } public string Title { get; set; } public string Description { get; set; } public string Letter { get; set; } /// <summary> /// 近义词 /// </summary> public string[] Synonyms { get; set; } public int Category { get; set; } public int Order { get; set; } }
HttpHelper
public class HttpHelper { /// <summary> /// POST方法获取某URL的页面内容 /// </summary> /// <param name="url">网址</param> /// <param name="parms">参数</param> /// <param name="encoding">编码</param> /// <returns>页面内容</returns> public static string PostResponse(string url, string parms, string encoding, string ContentType = "text/xml") { var result = string.Empty; try { var mRequest = (HttpWebRequest)WebRequest.Create(url); //相应请求的参数 var data = Encoding.GetEncoding(encoding).GetBytes(parms); mRequest.Method = "Post"; mRequest.ContentType = ContentType; mRequest.ContentLength = data.Length; mRequest.Timeout = ; mRequest.KeepAlive = true; mRequest.ProtocolVersion = HttpVersion.Version10; //请求流 var requestStream = mRequest.GetRequestStream(); requestStream.Write(data, , data.Length); requestStream.Close(); //响应流 var mResponse = mRequest.GetResponse() as HttpWebResponse; var responseStream = mResponse.GetResponseStream(); if (responseStream != null) { var streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding)); //获取返回的信息 result = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); } } catch { result = "获取数据失败,请重试!"; } return result; } /// <summary> /// Get方法获取某URL的页面内容 /// </summary> /// <param name="url">网址</param> /// <param name="encoding">编码</param> /// <returns>页面内容</returns> ) { try { System.Net.HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; req.Method = "GET"; req.ServicePoint.Expect100Continue = false; req.ServicePoint.UseNagleAlgorithm = false; req.Timeout = timeOut; string response = string.Empty; using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) { //Output(string.Format("{0},StatusCode:{1},{2}", url, res.StatusCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff"))); using (System.IO.StreamReader reader = new System.IO.StreamReader( res.GetResponseStream() , encoding)) { response = reader.ReadToEnd(); } return response; //Output(response); } } catch { return string.Empty; } } /// <summary> /// Get方法获取某URL的页面内容 /// </summary> /// <param name="url">网址</param> /// <param name="encoding">编码</param> /// <returns>页面内容</returns> public static string GetResponse(string url, string encoding, int timeOut) { string result = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = timeOut; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); Encoding encode = Encoding.GetEncoding(encoding); if (resStream != null) { StreamReader readStream = new StreamReader(resStream, encode); Char[] read = ]; , ); ) { String str = , count); result = result + str; count = readStream.Read(read, , ); } resStream.Close(); } } catch { return string.Empty; } return result; } /// <summary> /// 通过POST提交方式获取XML数据 /// </summary> /// <param name="requestXml">请求XML内容</param> /// <param name="url">请求URL</param> /// <param name="inputCharset">请求字符集</param> /// <returns></returns> public static XmlDocument GetXmlByPost(string requestXml, string url, string inputCharset) { if (string.IsNullOrEmpty(requestXml) || string.IsNullOrEmpty(url)) return null; if (string.IsNullOrEmpty(inputCharset)) inputCharset = "UTF-8"; try { string rtnStr = string.Empty; byte[] data = Encoding.GetEncoding(inputCharset).GetBytes(requestXml); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "Post"; myRequest.ContentType = "text/xml"; myRequest.ContentLength = data.Length; // 30秒超时时间 myRequest.Timeout = ().TotalMilliseconds; Stream newStream = myRequest.GetRequestStream(); // Send the data newStream.Write(data, , data.Length); newStream.Close(); // Get response HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding(inputCharset))) { rtnStr = reader.ReadToEnd(); reader.Close(); } XmlDocument xml = new XmlDocument(); xml.LoadXml(rtnStr); return xml; } catch { return null; } } /// <summary> /// xml 转化成 dataset /// </summary> /// <param name="xmlData">xml数据</param> /// <returns></returns> public static DataSet ConvertXMLToDataSet(string xmlData) { StringReader stream = null; XmlTextReader reader = null; try { DataSet xmlDS = new DataSet(); stream = new StringReader(xmlData); reader = new XmlTextReader(stream); xmlDS.ReadXml(reader); return xmlDS; } catch { return null; } finally { if (reader != null) reader.Close(); } } /// <summary> /// xml 转化成 datatable /// </summary> /// <param name="xmlData">xml数据</param> /// <returns></returns> public static DataTable ConvertXMLToDatatalbe(string xmlData) { StringReader stream = null; XmlTextReader reader = null; try { DataTable dt = new DataTable(); stream = new StringReader(xmlData); reader = new XmlTextReader(stream); dt.ReadXml(reader); return dt; } catch { return null; } finally { if (reader != null) reader.Close(); } } }
EnumUtil
public static class EnumUtil { /// <summary> /// 获取枚举的数据源 /// </summary> /// <returns>数据源</returns> public static List<EnumDataModel> GetEnumDataList<T>() { return EnumUtilData<T>.enumDataList; } /// <summary> /// 通过枚举获取描述信息 /// </summary> /// <param name="enumValue">枚举字段</param> /// <returns>描述信息</returns> public static string GetDescriptionByValue<T>(int value) { return GetDescriptionByName<T>(value.ToString()); } /// <summary> /// 通过枚举获取描述信息 /// </summary> /// <param name="enumValue">枚举字段</param> /// <returns>描述信息</returns> public static string GetDescriptionByName<T>(string name) { T t = GetEnumByName<T>(name); return GetDescriptionByEnum<T>(t); } /// <summary> /// 通过枚举获取描述信息 /// </summary> /// <param name="enumInstance">枚举</param> /// <returns>描述信息</returns> public static string GetDescriptionByEnum<T>(T enumInstance) { List<EnumDataModel> enumDataList = GetEnumDataList<T>(); EnumDataModel enumData = enumDataList.Find(m => m.Value == enumInstance.GetHashCode()); if (enumData != null) { return enumData.Description.ToString(); } else { return string.Empty; } } /// <summary> /// 通过枚举值得到枚举 /// </summary> /// <param name="value">枚举值</param> /// <returns>枚举</returns> public static T GetEnumByValue<T>(int value) { return GetEnumByName<T>(value.ToString()); } /// <summary> /// 通过枚举值得到枚举 /// </summary> /// <param name="name">枚举值</param> /// <returns>枚举</returns> public static T GetEnumByName<T>(string name) { string msg = string.Empty; try { Type t = typeof(T); return (T)System.Enum.Parse(t, name); } catch (Exception ex) { msg = ex.Message; return default(T); } } /// <summary> /// 尝试转换枚举,失败则返回false /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <param name="parsed"></param> /// <returns></returns> public static bool TryToEnum<T>(object value, out T parsed) where T : struct { bool isParsed = false; if (System.Enum.IsDefined(typeof(T), value)) { parsed = (T)System.Enum.Parse(typeof(T), value.ToString()); isParsed = true; } else { parsed = (T)System.Enum.Parse(]); } return isParsed; } /// <summary> /// 根据枚举获取下拉框 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="defaultValue"></param> /// <param name="addChoose"></param> /// <returns></returns> public static List<SelectListItem> SelectListEnum<T>(int? defaultValue = null, bool addChoose = true) where T : struct { var enumSelectListItem = new List<SelectListItem>(); if (addChoose) { var listItem = new SelectListItem { Text = "请选择", Value = "-1" }; enumSelectListItem.Add(listItem); } var enumDataList = EnumUtil.GetEnumDataList<T>(); enumSelectListItem.AddRange(from item in enumDataList let bl = defaultValue != null && item.Value == defaultValue select new SelectListItem { Text = item.Description, Value = item.Value.ToString(), Selected = bl }); return enumSelectListItem; } /// <summary> /// 内部实现类,缓存 /// </summary> /// <typeparam name="Tenum">枚举类型</typeparam> private static class EnumUtilData<Tenum> { /// <summary> /// 缓存数据 /// </summary> internal static readonly List<EnumDataModel> enumDataList; static EnumUtilData() { enumDataList = InitData(); } /// <summary> /// 初始化数据,生成枚举和描述的数据表 /// </summary> private static List<EnumDataModel> InitData() { List<EnumDataModel> enumDataList = new List<EnumDataModel>(); EnumDataModel enumData = new EnumDataModel(); Type t = typeof(Tenum); FieldInfo[] fieldInfoList = t.GetFields(); foreach (FieldInfo tField in fieldInfoList) { if (!tField.IsSpecialName) { enumData = new EnumDataModel(); enumData.Name = tField.Name; enumData.Value = ((Tenum)System.Enum.Parse(t, enumData.Name)).GetHashCode(); DescriptionAttribute[] enumAttributelist = (DescriptionAttribute[])tField.GetCustomAttributes(typeof(DescriptionAttribute), false); ) { enumData.Description = enumAttributelist[].Description; } else { enumData.Description = tField.Name; } enumDataList.Add(enumData); } } return enumDataList; } } /// <summary> /// 枚举数据实体 /// </summary> public class EnumDataModel { /// <summary> /// get or set 枚举名称 /// </summary> public string Name { get; set; } /// <summary> /// get or set 枚举值 /// </summary> public int Value { get; set; } /// <summary> /// get or set 枚举描述 /// </summary> public string Description { get; set; } } }
ValidatHelper
public class ValidatHelper { /// <summary> /// 检测字符串的内容是否数字字符 /// </summary> /// <param name="strTemp"></param> /// <returns></returns> public static bool IsNumeric(String strTemp) { if (String.IsNullOrEmpty(strTemp)) return false; strTemp = strTemp.Replace(",", String.Empty); Regex regNum = new Regex(@"^[-]?\d+[.]?\d*$"); return regNum.IsMatch(strTemp); } /// <summary> /// 判断一个字符串是否为邮件 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsEmail(string email) { Regex regex = new Regex(@"^\w+([-+.]\w+)*@(\w+([-.]\w+)*\.)+([a-zA-Z]+)+$", RegexOptions.IgnoreCase); return regex.Match(email).Success; } /// <summary> /// 判断一个字符串是否为Deceimal 类型 /// </summary> /// <param name="_value">要判断的原数据</param> /// <returns>是否为Decimal类型</returns> public static bool IsDecimal(string _value) { decimal tmp; if (decimal.TryParse(_value, out tmp)) return true; else return false; } /// <summary> /// 是否是中文字符 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsCNChar(String str) { string strRegTxt = @"^[\u4e00-\u9fa5]{0,}$"; if (!Regex.IsMatch(str, strRegTxt)) { return false; } else { return true; } } /// <summary> /// 检查一个字符串是否可以转化为日期,一般用于验证用户输入日期的合法性。 /// </summary> /// <param name="_value">需验证的字符串。</param> /// <returns>是否可以转化为日期的bool值。</returns> public static bool IsStringDate(string _value) { DateTime dTime; try { dTime = DateTime.Parse(_value); } catch (FormatException) { return false; } return true; } /// <summary> /// 判断一个字符串是否为8位无符号整数 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsByte(string _value) { byte tmp; if (Byte.TryParse(_value, out tmp)) return true; else return false; } /// <summary> /// 判断一个字符串是否为短整型整数 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsInt16(string _value) { short tmp; if (Int16.TryParse(_value, out tmp)) return true; else return false; } /// <summary> /// 判断一个字符串是否为整数 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsInt32(string _value) { int tmp; if (Int32.TryParse(_value, out tmp)) return true; else return false; } /// <summary> /// 判断一个字符串是否为长整数 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsInt64(string _value) { long tmp; if (Int64.TryParse(_value, out tmp)) return true; else return false; } /// <summary> /// 判断一个字符是否是bool类型 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsBoolean(string _value) { bool temp; if (bool.TryParse(_value, out temp)) return true; else return false; } /// <summary> /// 判断一个字符串是否为手机号码 /// </summary> /// <param name="mobileNum"></param> /// <returns></returns> public static bool IsMobileNum(string mobileNum) { Regex regex = new Regex(@"^(13|14|15|18|17)[0-9]{9}$", RegexOptions.IgnoreCase); return regex.Match(mobileNum).Success; } /// <summary> /// 判断一个字符串是否为电话号码 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsPhoneNum(string _value) { Regex regex = new Regex(@"^(86)?(-)?(0\d{2,3})?(-)?(\d{7,8})(-)?(\d{3,5})?$", RegexOptions.IgnoreCase); return regex.Match(_value).Success; } /// <summary> /// 判断一个字符串是否为网址 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsUrl(string _value) { Regex regex = new Regex(@"(http://)?([\w-]+\.)*[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase); return regex.Match(_value).Success; } /// <summary> /// 是否是英文 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsEnChar(string _value) { Regex regex = new Regex(@"[a-zA-Z]{1,}"); return regex.Match(_value).Success; } /// <summary> /// 判断一个字符串是否为IP地址 /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsIP(string _value) { Regex regex = new Regex(@"^(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1})).(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1})).(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1})).(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1}))$", RegexOptions.IgnoreCase); return regex.Match(_value).Success; } /// <summary> /// 判断一个字符串是否为字母加数字 /// Regex("[a-zA-Z0-9]?" /// </summary> /// <param name="_value"></param> /// <returns></returns> public static bool IsWordAndNum(string _value) { Regex regex = new Regex("[a-zA-Z0-9]?"); return regex.Match(_value).Success; } /// <summary> /// 验证是否为金钱类型 /// </summary> /// <param name="strMoney"></param> /// <returns></returns> public static bool IsMoney(string strMoney) { ; try { money = Convert.ToSingle(strMoney); } catch (FormatException) { return false; } return true; } /// <summary> /// 验证邮政编码 /// </summary> /// <param name="strPostNo"></param> /// <returns></returns> public static bool IsPostNo(string strPostNo) { ) return false; Regex regex = new Regex(@"[1-9]\d{5}(?!\d)"); return regex.Match(strPostNo).Success; } /// <summary> /// yyyyMMdd是否为合法的日期 /// </summary> /// <param name="date">要检验的日期</param> /// <returns></returns> public static bool IsDate(string date) { DateTime dt; if (string.IsNullOrEmpty(date)) return false; System.Globalization.CultureInfo zhCN = new System.Globalization.CultureInfo("zh-CN"); string[] formats = { "yyyyMMdd", "yyyyMMddHH", "yyyyMMddHHmm", "yyyyMMddHHmmss" }; return DateTime.TryParseExact(date, formats, zhCN, System.Globalization.DateTimeStyles.None, out dt); } /// <summary> /// 判断是否为字母 /// </summary> /// <param name="value">要校验的字符串</param> /// <returns></returns> public static bool IsLetters(string value) { return System.Text.RegularExpressions.Regex.IsMatch(value, @"^[a-zA-Z]"); } /// <summary> /// 是否是日期类型 /// </summary> /// <returns></returns> public static bool IsDateTime(string strDateValue) { string strRealValue = null; if (IsNullOrEmptyString(strDateValue, out strRealValue)) return false; DateTime dtDate = DateTime.MinValue; return DateTime.TryParse(strRealValue, out dtDate); } /// <summary> /// DataRow的value或从数据库中取出的Object型数据验证,验证取出的object是否是DBNull,空或null] /// 如果是DBNull,null或空字符串则返回true /// </summary> /// <param name="objSource">待验证的object</param> /// <returns> /// 如果是DBNull,null或空字符串则返回true /// </returns> public static bool IsDBNullOrNullOrEmptyString(object objSource) { if ((objSource == DBNull.Value) || (objSource == null)) return true; string strSource = objSource.ToString(); if (strSource.Trim() == string.Empty) return true; return false; } /// <summary> /// 验证是否是空或null字符串 /// 如果是空或null则返回true,否则返回false /// </summary> /// <param name="strSource">待查看的string</param> /// <returns> /// 如果是空或null则返回true,否则返回false /// </returns> public static bool IsNullOrEmptyString(string strSource) { if (strSource == null) return true; if (strSource.Trim() == string.Empty) return true; return false; } /// <summary> /// 验证是否是空或null字符串 /// 如果是空或null则返回true,strRealString为null或string.Empty /// 否则返回false,strRealString为经过Trim操作的String; /// </summary> /// <param name="strSource">待查看的string</param> /// <param name="strRealString">经过Trim操作的string</param> /// <returns> /// 如果是空或null则返回true,strRealString为null或string.Empty /// 否则返回false,strRealString为经过Trim操作的String; /// </returns> public static bool IsNullOrEmptyString(string strSource, out string strRealString) { strRealString = null; if (strSource == null) return true; strRealString = strSource.Trim(); if (strRealString == string.Empty) return true; return false; } #region ip转换成long /// <summary> /// ip转换成long /// </summary> /// <param name="ipAdd"></param> /// <returns></returns> public static long GetIpNum(string ipAdd) { string[] ipArr = ipAdd.Split('.'); ) { ]); ]); ]); ]); * * + b * * + c * + d; } else { ; } } #endregion /// <summary> /// 判断IP是否在范围之内 /// </summary> /// <param name="ipAdd"></param> /// <param name="begin"></param> /// <param name="end"></param> /// <returns></returns> public static bool IsInIP(long ipAdd, long begin, long end) { return ipAdd >= begin && ipAdd <= end; } #region 判断是否是IP地址格式 0.0.0.0 /// <summary> /// 判断是否是IP地址格式 0.0.0.0 /// </summary> /// <param name="str1">待判断的IP地址</param> /// <returns>true or false</returns> public static bool IsIPAddress(string str1) { || str1.Length > ) return false; string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$"; Regex regex = new Regex(regformat, RegexOptions.IgnoreCase); return regex.IsMatch(str1); } #endregion #region 判断是否有特殊字符 /// <summary> ///判断是否有特殊字符 /// </summary> /// <param name="text"></param> /// <returns></returns> public static bool IsInvalidString(string text) { bool isInvalidstring = false; if (string.IsNullOrWhiteSpace(text)) return false; if (Regex.IsMatch(text, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']")) isInvalidstring = true; if (Regex.IsMatch(text, @"<script[^>]*?>.*?</script>") || Regex.IsMatch(text, @"<style[\s\S]+</style *>") || Regex.IsMatch(text, @"<(.[^>]*)>") || Regex.IsMatch(text, @"([\r\n])[\s]+") || Regex.IsMatch(text, @"-->") || Regex.IsMatch(text, @"<!--.*") || Regex.IsMatch(text, @"&(quot|#34);") || Regex.IsMatch(text, @"&(amp|#38);") || Regex.IsMatch(text, @"&(lt|#60);") || Regex.IsMatch(text, @"&(gt|#62);") || Regex.IsMatch(text, @"&(nbsp|#160);") || Regex.IsMatch(text, @"&(iexcl|#161);") || Regex.IsMatch(text, @"&(cent|#162);") || Regex.IsMatch(text, @"&(pound|#163);") || Regex.IsMatch(text, @"&(copy|#169);") || Regex.IsMatch(text, @"<") || Regex.IsMatch(text, @">") || Regex.IsMatch(text, @"\r\n") ) { isInvalidstring = true; } return isInvalidstring; } #endregion #region 判断是否含有SQL字符 private static string[] _nvalidSqlString = new string[] { Regex.Escape("/*"), Regex.Escape(@"*/"), "--", "'", "declare", "select", "into", "insert", "update", "delete", "drop", "create", "exec", "master" }; public static bool IsInvalidSqlString(string text) { if (string.IsNullOrWhiteSpace(text)) { goto end; } if (Regex.IsMatch(text, string.Join("|", _nvalidSqlString))) { return true; } end: return false; } #endregion #region 用户手机号码加密 public static string EncryptMobile(string Mobile) { Regex regex = new Regex(@"(?<=13\d|15\d|18\d|147)\d{4}(?=\d{4})", RegexOptions.Compiled | RegexOptions.IgnoreCase); if (regex.IsMatch(Mobile)) { return regex.Replace(Mobile, "****"); } else { return Mobile; } } #endregion #region 用户证件号加密 public static string EncryptCardNo(string CardNo) { Regex regex = new Regex(@"(?<!^).(?!$)"); return regex.Replace(CardNo, "*"); } #endregion #region 验证乘客姓名是否为繁体字 /// <summary> /// 验证乘客姓名是否为繁体字 /// </summary> /// <param name="name">乘客姓名</param> /// <returns>非GB2312的字符</returns> public static string GB2312_Check(string name) { string temp = Regex.Replace(name, "[A-Za-z]|/| ", ""); ) return string.Empty; string strError = string.Empty; byte[] bttemp = System.Text.Encoding.Default.GetBytes(temp); ; i < bttemp.Length; i = i + ) { && bttemp[i] <= && bttemp[i + ] >= && bttemp[i + ] <= ) { continue; } else { strError += temp[i / ]; } } return strError; } #endregion #region 是否省份 /// <summary> /// timmy 20130516 /// </summary> /// <param name="province"></param> /// <returns></returns> public static bool IsProvince(string province) { string[] provinceList = { "安徽", "北京", "福建", "甘肃", "广东", "广西", "贵州", "海南", "河北", "河南", "黑龙江", "湖北", "湖南", "吉林", "江苏", "江西", "辽宁", "内蒙古", "宁夏", "青海", "山东", "山西", "陕西", "上海", "四川", "天津", "*", "*", "云南", "浙江", "重庆", "香港", "澳门", "*" }; if (!string.IsNullOrEmpty(province) && provinceList.Contains(province)) { return true; } else { return false; } } #endregion #region 数字验证 /// <summary> /// 是否是数字 /// </summary> /// <param name="strNum">待测试的字符串</param> /// <returns>是则返回true,否则返回false</returns> public static bool IsNumber(string strNum) { if (strNum == null) return false; return Regex.IsMatch(strNum.Trim(), "^(0|[1-9][0-9]*)$"); } #endregion }
.net工具类的更多相关文章
-
Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
-
Android—关于自定义对话框的工具类
开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...
-
[转]Java常用工具类集合
转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...
-
js常用工具类.
一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...
-
Guava库介绍之实用工具类
作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...
-
Java程序员的日常—— Arrays工具类的使用
这个类在日常的开发中,还是非常常用的.今天就总结一下Arrays工具类的常用方法.最常用的就是asList,sort,toStream,equals,copyOf了.另外可以深入学习下Arrays的排 ...
-
.net使用正则表达式校验、匹配字符工具类
开发程序离不开数据的校验,这里整理了一些数据的校验.匹配的方法: /// <summary> /// 字符(串)验证.匹配工具类 /// </summary> public c ...
-
WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
-
JAVA 日期格式工具类DateUtil.java
DateUtil.java package pers.kangxu.datautils.utils; import java.text.SimpleDateFormat; import java.ut ...
-
安卓---Toast工具类,有点懒
package com.liunan.myfirstapp.util; import android.content.Context; import android.widget.Toast; /** ...
随机推荐
-
Data Validate 之 Data Annotation
什么是Data Annotation ? 如何使用 ? 自定义Validate Attribute EF Db first中使用Data Annotation asp.net MVC中使用Data ...
-
iOS开发——高级篇——iPad开发、iPad开发中的modal
一.iPad简介 1.什么是iPad一款苹果公司于2010年发布的平板电脑定位介于苹果的智能手机iPhone和笔记本电脑产品之间跟iPhone一样,搭载的是iOS操作系统 2.iPhone和iPadi ...
-
1. ReactNative 基础
/** 1. reactNative 反应式语言 2. 既拥有原生的用户体验,又保留React的开发效率 3. FaceBook研究 H5,Android,iOS 4. BAT的插件化,热修改 2 ...
-
Swift语法简介(二)闭包
突然看到别人写的关于Block的帖子,让我突然有一种想写一篇关于闭包的帖子.在我的认知中,Swift中的闭包,就是Object-C中的Block--(或许我的认知太浅了).先上一个闭包的简单例子 le ...
-
Make命令
Make命令 一.Make的概念 Make这个词,英语的意思是"制作".Make命令直接用了这个意思,就是要做出某个文件.比如,要做出文件a.txt,就可以执行下面的命令. $ m ...
-
用Visio画UML顺序图
1.顺序图 顺序图又称为时序图,顾名思义,它着重表现的是对象间消息传递的时间顺序.顺序图描述的对象也是一个用例,即一组行为操作,而它表现的是这组行为的先后关系(纵坐标),以及每个行为是属于哪个对象的( ...
-
适配iOS9遇到的一些问题_Scheme白名单_ Bitcode及解决办法
升级Xcode7 运行项目发现报错如下: 1.Scheme白名单问题 -canOpenURL: failed for URL: “weixin://app/wxdaae92a9cfe5d54c/” - ...
-
docker初步
[Note,]由于docker的局限性,docker只能运行在64位的系统中 docker软件应用程序可以重复地运行在任何地方,因为它的容器包含了所有的环境依赖关系! docker有三种方式运行 作为 ...
-
Mysql数据库学习笔记之数据库索引(index)
什么是索引: SQL索引有两种,聚集索引和非聚集索引,索引主要目的是提高了SQL Server系统的性能,加快数据的查询速度与减少系统的响应时间. 聚集索引:该索引中键值的逻辑顺序决定了表中相应行的物 ...
-
关于Java,那些我心存疑惑的事(不断更新中...)
本文主要列出一些Java常用到确又让大家不怎么注意的问题. 将会不断更新,欢迎关注-- 如有觉得不合理之处,欢迎评论交流,没有火花怎么印象深刻? (1)Java到底是值传递?还是引用传递? 揪出这个问 ...