Optimized Code:
Public static class converter {// <summary> // convert to another type that inherits iconvertible /// </Summary> /// <typeparam name = "T"> convert </typeparam> /// <Param name = "value"> value to be converted </param> /// <Param name = "success"> Successful </ 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> /// convert to another type that inherits iconvertible /// </Summary> /// <typeparam name = "T"> Conversion Type </typeparam >/// <Param name = "value"> value to be converted </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> ();}}Test the running efficiency
Go to the previous test code
First: 3519
Second: 3570
Third: 3783
The comparison is improved by about 6 times when it is not optimized, and the optimization for saving the methodinfo object is improved by about 4 times.