/// <summary> /// 执行转换 /// </summary> /// <typeparam name="Tin"></typeparam> /// <typeparam name="Tout"></typeparam> /// <param name="src"></param> /// <param name="format"></param> /// <returns></returns> public static Tout ConvertTo <Tin, Tout>(this Tin src, String format = "", Properties context = null) { if (typeof(Tin) == typeof(Tout)) { return((Tout)(Object)src); } if (typeof(Tout) == typeof(Object)) { return((Tout)(Object)src); } DoConvertor <Tin, Tout> convert = GetConvert <Tin, Tout>(); if (convert != null) { return(convert(src, format, context)); } if (src.Equals(default(Tin))) { return(default(Tout)); } if (typeof(Tout) == typeof(String))//如果目标类型是字符串 { if (typeof(Tin).GetMethod("ToString").DeclaringType == typeof(Tin)) { return((Tout)(Object)src.ToString());//如果源类型实现了ToString,则直接调用 } return((Tout)(Object)objectToStr(src, format, context)); } else if (typeof(Tin) == typeof(String)) { MethodInfo method = typeof(Tout).GetMethod("Parse", BindingFlags.Static); if (method != null)//如果目标类型实现静态方法Parse,则直接调用 { return((Tout)method.Invoke(null, new Object[] { src })); } return((Tout)strToObject(src.ToString(), typeof(Tout), format, context)); } else if (typeof(Tout) == typeof(int)) { return((Tout)(Object)strToInt(src == null ? "0" : src.ToString(), format, context)); } else if (typeof(Tout) == typeof(double) || typeof(Tout) == typeof(float)) { return((Tout)(Object)strTodouble(src == null ? "0" : src.ToString(), format, context)); } else if (typeof(Tout) == typeof(DateTime)) { return((Tout)(Object)strToDatetime(src == null ? "" : src.ToString(), format, context)); } else if (typeof(Tout).IsEnum) { return((Tout)(Object)strtoenum <Tout>(src == null ? "" : src.ToString(), format, context)); } throw new NotImplementedException(); }
/// <summary> /// 转换器注册 /// </summary> /// <typeparam name="Tin"></typeparam> /// <typeparam name="Tout"></typeparam> /// <param name="converter"></param> public static void RegisteConvertor <Tin, Tout>(DoConvertor <Tin, Tout> converter) { KeyValuePair <KeyValuePair <Type, Type>, Delegate> r = converters.FirstOrDefault <KeyValuePair <KeyValuePair <Type, Type>, Delegate> >(kvp => kvp.Key.Key == typeof(Tin) && kvp.Key.Key == typeof(Tout)); if (r.Value != null) { converters[r.Key] = converter; return; } KeyValuePair <Type, Type> key = new KeyValuePair <Type, Type>(typeof(Tin), typeof(Tout)); converters.Add(key, converter); }
/// <summary> /// 取得转换器 /// </summary> /// <typeparam name="Tin"></typeparam> /// <typeparam name="Tout"></typeparam> /// <param name="includeDefault"></param> /// <returns></returns> public static DoConvertor <Tin, Tout> GetConvert <Tin, Tout>(bool includeDefault = true) { DoConvertor <Tin, Tout> conv = doGetConvert <Tin, Tout>(converters, false, false); if (conv != null) { return(conv); } if (!includeDefault) { return(null); } conv = doGetConvert <Tin, Tout>(defaultconverters, false, false); if (conv != null) { return(conv); } return(null); }