[Continued] compile a General C # preprocessing type Conversion Method Using Generics (use delegation to improve performance ),
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.
How do I use generics in C?
Class a <T>
{
Public void d (T c)
{
}
A <T> a1 = new A <T> (); // T can be of various types int float...
}
C # For simple generic programming #
Public class Test <T>: List <T>
{
Public int Count
{
Get {return base. Count ;}
}
Public void Add (T value)
{
If (Count <10)
Base. Add (value );
Else
Throw new IndexOutOfRangeException ();
}
}
------------------
I wrote it myself and passed the test. I hope it will help you :)