Created
February 20, 2012 13:26
-
-
Save huyderman/1869189 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static readonly Type StringType = typeof(string); | |
private static readonly Dictionary<Type, bool> IsStringAssignable = new Dictionary<Type, bool> { { StringType, true } }; | |
private static readonly Dictionary<Type, ConstructorInfo> SingleStringConstructor = new Dictionary<Type, ConstructorInfo>(); | |
private static readonly Dictionary<Type, MethodInfo> ParseMethod = new Dictionary<Type, MethodInfo>(); | |
public static T Get<T>(string setting) | |
{ | |
object value = ConfigurationManager.AppSettings.Get(setting); | |
if (value == null) | |
return default(T); | |
var t = typeof(T); | |
if (!IsStringAssignable.ContainsKey(t)) | |
IsStringAssignable[t] = t.IsAssignableFrom(StringType); | |
if (IsStringAssignable[t]) | |
return (T)value; | |
if (!SingleStringConstructor.ContainsKey(t)) | |
SingleStringConstructor[t] = t.GetConstructors().SingleOrDefault(HasSingleArgument<string>); | |
if (SingleStringConstructor[t] != null) | |
{ | |
return (T)SingleStringConstructor[t].Invoke(new[] { value }); | |
} | |
if (!ParseMethod.ContainsKey(t)) | |
{ | |
ParseMethod[t] = t.GetMethods().SingleOrDefault(IsParseMethod); | |
} | |
if (ParseMethod[t] != null) | |
{ | |
return (T)ParseMethod[t].Invoke(null, new[] { value }); | |
} | |
return default(T); | |
} | |
private static bool IsParseMethod(MethodInfo m) | |
{ | |
return m.Name == "Parse" && m.IsStatic && HasSingleArgument<string>(m) && m.ReturnType == StringType; | |
} | |
private static bool HasSingleArgument<T>(MethodBase method) | |
{ | |
var parameters = method.GetParameters(); | |
return parameters.Count() == 1 && parameters.First().ParameterType == typeof(T); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment