Last active
April 30, 2017 20:01
-
-
Save dasjestyr/90d8ef4dea179a6e08ddd85e0dacbc94 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
public class TryParseFactory | |
{ | |
public delegate bool TryParseDelegate<T>(string s, out T result); | |
private readonly Dictionary<Type, Delegate> _tryParsers = new Dictionary<Type, Delegate>(); | |
public TryParseFactory() | |
{ | |
Register<Guid>(Guid.TryParse); | |
Register<int>(int.TryParse); | |
Register<uint>(uint.TryParse); | |
Register<long>(long.TryParse); | |
Register<ulong>(ulong.TryParse); | |
Register<decimal>(decimal.TryParse); | |
Register<double>(double.TryParse); | |
Register<float>(float.TryParse); | |
} | |
public void Register<T>(TryParseDelegate<T> d) | |
{ | |
_tryParsers[typeof(T)] = d; | |
} | |
public bool Deregister<T>() | |
{ | |
return _tryParsers.Remove(typeof(T)); | |
} | |
public bool TryParse<T>(string s, out T result) | |
{ | |
if (!_tryParsers.ContainsKey(typeof(T))) | |
{ | |
throw new ArgumentException("Does not contain parser for " + typeof(T).FullName + "."); | |
} | |
var d = (TryParseDelegate<T>)_tryParsers[typeof(T)]; | |
return d(s, out result); | |
} | |
public bool TryParse(Type type, string s, out object result) | |
{ | |
if (!_tryParsers.ContainsKey(type)) | |
{ | |
throw new ArgumentException("Does not contain parser for " + type.FullName + "."); | |
} | |
var method = GetType().GetTypeInfo() | |
.GetDeclaredMethods("TryParse") | |
.First(m => m.IsGenericMethod) | |
.MakeGenericMethod(type); | |
object outParameter = null; | |
var arguments = new[] { s, outParameter }; | |
var parseSucceeded = (bool) method.Invoke(this, arguments); | |
result = arguments[1]; | |
return parseSucceeded; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment