using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GSYWApi { /// /// /// public static class TypeParseExtenions { /// /// /// public static bool IsEmpty(this object[] me) { if (me == null) return true; if (me.Length == 0) return true; return false; } /// /// /// public static bool IsNullOrDBNull(this object me) { return !(me != null && me != DBNull.Value); } /// /// /// public static T As(this object me) { return As(me, default(T)); } /// /// /// public static T As(this object me, T defaultValue) { T v; try { v = (T)Convert.ChangeType(me, typeof(T)); } catch { v = defaultValue; } return v; } /// /// /// public static DateTime? TryParseToDateTime(this object me) { if (me.IsNullOrDBNull()) { return null; } else if (me is DateTime) { return (DateTime)me; } else { DateTime v; if (DateTime.TryParse(me.ToString(), out v)) { return v; } else { return null; } } } /// /// /// public static string TryParseToString(this object me) { return me == null ? string.Empty : Convert.ToString(me); } /// /// /// public static bool TryParseToBool(this object me, bool defaultValue = false) { if (me.IsNullOrDBNull()) return defaultValue; if (me is int) { return (int)me > 0 ? true : false; } else { bool v; bool.TryParse(me.ToString(), out v); return v; } } /// /// /// public static short? TryParseToShort(this object me, short? defaultValue = null) { short? v = defaultValue; try { v = short.Parse(decimal.Parse(me.ToString()).ToString("0")); } catch { } return v; } /// /// /// public static int? TryParseToInt(this object me, int? defaultValue = null) { int? v = defaultValue; try { v = int.Parse(decimal.Parse(me.ToString()).ToString("0")); } catch { } return v; } /// /// /// public static long? TryParseToLong(this object me, long? defaultValue = null) { long? v = defaultValue; try { v = long.Parse(decimal.Parse(me.ToString()).ToString("0")); } catch { } return v; } /// /// /// public static decimal? TryParseToDecimal(this object me, decimal? defaultValue = null) { decimal? v = defaultValue; try { v = decimal.Parse(me.ToString()); } catch { } return v; } /// /// /// public static double? TryParseToDouble(this object me, double? defaultValue = null) { double? v = defaultValue; try { v = double.Parse(me.ToString()); } catch { } return v; } } }