优化后的代码:
public static class Converter { /// <summary> /// 转换为其他继承IConvertible的类型 /// </summary> /// <typeparam name="T">转换的类型</typeparam> /// <param name="value">要转换的值</param> /// <param name="success">是否成功</param> /// <returns></returns> public static T To<T>(this IConvertible value, out bool success) where T : IConvertible { if (value == null) { success = true; return default(T); } Type tResult = typeof(T); if (tResult == typeof(string)) { success = true; return (T)(object)value.ToString(); } TryParseDelegate<T> tryParseDelegate; if (_TryParse.ContainsKey(tResult.FullName)) { tryParseDelegate = (TryParseDelegate<T>)_TryParse[tResult.FullName]; } else { MethodInfo mTryParse = tResult.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new Type[] { typeof(string), tResult.MakeByRefType() }, new ParameterModifier[] { new ParameterModifier(2) }); tryParseDelegate = (TryParseDelegate<T>)Delegate.CreateDelegate(typeof(TryParseDelegate<T>), mTryParse); _TryParse.Add(tResult.FullName, tryParseDelegate); } T result; success = tryParseDelegate(value.ToString(), out result); return result; } /// <summary> /// 转换为其他继承IConvertible的类型 /// </summary> /// <typeparam name="T">转换的类型</typeparam> /// <param name="value">要转换的值</param> /// <returns></returns> public static T To<T>(this IConvertible value) where T : IConvertible { bool success; return To<T>(value, out success); } private delegate bool TryParseDelegate<T>(string s, out T tResult) where T:IConvertible; private static Dictionary<string, object> _TryParse = new Dictionary<string, object>(); } }
运行效率测试
测试代码请转到上一篇
第一次:3519
第二次:3570
第三次:3783
对比完全没优化过的时候大概提高了6倍,把MethodInfo对象保存起来保存起来的优化大概提高了4倍
【续】使用泛型编写通用的C#预处理类型转换方法(使用委托提高性能)
时间: 2024-11-05 22:38:42