C# TypeConverter 数据转换
提供一种将值的类型转换为其他类型以及访问标准值和子属性的统一方法。
自定义Converter:
public class GenericListTypeConverter<T> : TypeConverter { protected readonly TypeConverter typeConverter; public GenericListTypeConverter() { typeConverter = TypeDescriptor.GetConverter(typeof(T)); if (typeConverter == null) throw new InvalidOperationException("No type converter exists for type " + typeof(T).FullName); } protected virtual string[] GetStringArray(string input) { if (!String.IsNullOrEmpty(input)) { string[] result = input.Split(','); Array.ForEach(result, s => s.Trim()); return result; } else return new string[0]; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { string[] items = GetStringArray(sourceType.ToString()); return items.Any(); } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string[] items = GetStringArray((string)value); var result = new List<T>(); Array.ForEach(items, s => { object item = typeConverter.ConvertFromInvariantString(s); if (item != null) { result.Add((T)item); } }); return result; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { string result = string.Empty; if (((IList<T>)value) != null) { //we don't use string.Join() because it doesn't support invariant culture for (int i = 0; i < ((IList<T>)value).Count; i++) { var str1 = Convert.ToString(((IList<T>)value)[i], CultureInfo.InvariantCulture); result += str1; //don't add comma after the last element if (i != ((IList<T>)value).Count - 1) result += ","; } } return result; } return base.ConvertTo(context, culture, value, destinationType); } }
var a = new Converter.GenericListTypeConverter<int>().ConvertFrom("1,2,3"); List<int> b = (List<int>)a;
public class ShippingOptionTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { ShippingOption shippingOption = null; string valueStr = value as string; if (!String.IsNullOrEmpty(valueStr)) { try { using (var tr = new StringReader(valueStr)) { var xmlS = new XmlSerializer(typeof(ShippingOption)); shippingOption = (ShippingOption)xmlS.Deserialize(tr); } } catch { //xml error } } return shippingOption; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { var shippingOption = value as ShippingOption; if (shippingOption != null) { var sb = new StringBuilder(); using (var tw = new StringWriter(sb)) { var xmlS = new XmlSerializer(typeof(ShippingOption)); xmlS.Serialize(tw, value); string serialized = sb.ToString(); return serialized; } } else { return ""; } } return base.ConvertTo(context, culture, value, destinationType); } } public class ShippingOptionListTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { List<ShippingOption> shippingOptions = null; string valueStr = value as string; if (!String.IsNullOrEmpty(valueStr)) { try { using (var tr = new StringReader(valueStr)) { var xmlS = new XmlSerializer(typeof(List<ShippingOption>)); shippingOptions = (List<ShippingOption>)xmlS.Deserialize(tr); } } catch { //xml error } } return shippingOptions; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { var shippingOptions = value as List<ShippingOption>; if (shippingOptions != null) { var sb = new StringBuilder(); using (var tw = new StringWriter(sb)) { var xmlS = new XmlSerializer(typeof(List<ShippingOption>)); xmlS.Serialize(tw, value); string serialized = sb.ToString(); return serialized; } } else { return ""; } } return base.ConvertTo(context, culture, value, destinationType); } }
http://www.cnblogs.com/takako_mu/archive/2012/10/08/2715594.html
扩展:GenericEnumConverter
http://msdn.microsoft.com/zh-cn/library/system.configuration.genericenumconverter(v=VS.80).aspx
扩展函数定义简单数据类型转换:
public static class ExtensionMethods { #region 转换函数 /// <summary> /// object 转换为 int /// </summary> /// <returns></returns> private static int ObjToInt(object obj) { if (obj == null) return 0; if (obj.Equals(DBNull.Value)) return 0; int returnValue; if (int.TryParse(obj.ToString(), out returnValue)) { return returnValue; } else { return 0; } } /// <summary> /// 转换为boolean型 /// </summary> /// <param name="obj"></param> /// <returns></returns> private static bool ObjToBool(object obj) { if (obj == null) return false; if (obj.Equals(DBNull.Value)) return false; bool returnValue; if (bool.TryParse(obj.ToString(), out returnValue)) { return returnValue; } else { return false; } } /// <summary> /// object 转换为 int? /// </summary> /// <param name="obj"></param> /// <returns></returns> private static int? ObjToIntNull(object obj) { if (obj == null) return null; if (obj.Equals(DBNull.Value)) return null; return ObjToInt(obj); } /// <summary> /// object 转换为 string /// </summary> /// <param name="obj"></param> /// <returns></returns> private static string ObjToStr(object obj) { if (obj == null) return ""; if (obj.Equals(DBNull.Value)) return ""; return Convert.ToString(obj); } /// <summary> /// object 转换为 decimal /// </summary> /// <param name="obj"></param> /// <returns></returns> private static decimal ObjToDecimal(object obj) { if (obj == null) return 0; if (obj.Equals(DBNull.Value)) return 0; try { return Convert.ToDecimal(obj); } catch { return 0; } } /// <summary> /// object 转换为 decimal? /// </summary> /// <param name="obj"></param> /// <returns></returns> private static decimal? ObjToDecimalNull(object obj) { if (obj == null) return null; if (obj.Equals(DBNull.Value)) return null; return ObjToDecimal(obj); } /// <summary> /// 转换为日期 /// </summary> /// <param name="obj"></param> /// <returns></returns> private static DateTime? ObjToDateNull(object obj) { if (obj == null) { return null; } try { return Convert.ToDateTime(obj); } catch { return null; } } #endregion #region 数据转换扩展函数 /// <summary> /// object 转换为 int /// </summary> /// <returns></returns> public static int ToInt(this object obj) { return ObjToInt(obj); } /// <summary> /// object 转换为 string /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string ToStr(this object obj) { return ObjToStr(obj); } /// <summary> /// object 转换为 decimal /// </summary> /// <param name="obj"></param> /// <returns></returns> public static decimal ToDecimal(this object obj) { return ObjToDecimal(obj); } /// <summary> /// object 转换为 int? /// </summary> /// <param name="obj"></param> /// <returns></returns> public static int? ToIntNull(this object obj) { return ObjToIntNull(obj); } /// <summary> /// object 转换为 decimal? /// </summary> /// <param name="obj"></param> /// <returns></returns> public static decimal? ToDecimalNull(this object obj) { return ObjToDecimalNull(obj); } /// <summary> /// 转换为boolean型 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static bool ToBool(this object obj) { return ObjToBool(obj); } /// <summary> /// 转换为日期 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static DateTime? ToDateNull(this object obj) { return ObjToDateNull(obj); } /// <summary> /// 转换为Double /// </summary> /// <param name="value"></param> /// <returns></returns> public static double ToDouble(this decimal value) { return Convert.ToDouble(value); } #endregion }
1.职业成功的85%取决于职业心态,15%取决于职业技能
2.不只是上级要你去做或等待别人要你去做
3.营造积极友善的工作氛围,哪怕吹点善意的牛