標籤:style blog http color 使用 os
最佳化後的代碼:
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倍