/// <summary> /// Parse any string to a base type utulizing the types built in TryParse Method /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="thingToParse">The string you want to parse</param> /// <param name="defaultValue">The default value to return if parsing fails</param> /// <returns></returns> public static T Parse <T>(this string thingToParse, T defaultValue) { var retType = typeof(T); if (KnownParsers.ContainsKey(retType) != true) { KnownParsers[retType] = GetTryParse(retType); } MethodInfo tParse = KnownParsers[retType]; if (tParse != null) { var parameters = new object[] { thingToParse, null }; var success = (bool)tParse.Invoke(null, parameters); if (success) { return((T)parameters[1]); } } return(defaultValue); }
public static T Parse <T>(this string thingToParse, T defaultValue) { var retType = typeof(T); if (KnownParsers.ContainsKey(retType) != true) { KnownParsers[retType] = retType.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string), retType.MakeByRefType() }, null); } MethodInfo tParse = KnownParsers[retType]; if (tParse != null) { var parameters = new object[] { thingToParse, null }; var success = (bool)tParse.Invoke(null, parameters); if (success) { return((T)parameters[1]); } } return(defaultValue); }