Created
March 3, 2016 01:45
-
-
Save thzinc/82f9b4b22361742bc87b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System.Collections.Generic; | |
using System.Reflection; | |
using System.Linq; | |
namespace Sonorous.Core.Services | |
{ | |
public static class StructExtensions | |
{ | |
public delegate bool TryParseDelegate<T>(string input, out T value); | |
public static T? TryParse<T>(this string input) | |
where T : struct | |
{ | |
var methodInfo = typeof(T).GetMethods(BindingFlags.Static | BindingFlags.Public) | |
.FirstOrDefault(mi => mi.Name == "TryParse" && mi.GetParameters().Length == 2); | |
if (methodInfo == null) | |
return null; | |
var selector = (TryParseDelegate<T>)methodInfo.CreateDelegate(typeof(TryParseDelegate<T>)); | |
return input.TryParse(selector); | |
} | |
public static T? TryParse<T>(this string input, TryParseDelegate<T> selector) | |
where T : struct | |
{ | |
T result; | |
if (selector(input, out result)) | |
return result; | |
return null; | |
} | |
public static IEnumerable<T?> AsNullable<T>(this IEnumerable<T> items) | |
where T : struct | |
{ | |
return items.Cast<T?>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment