-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding enum parser that is case insensitive.
- Loading branch information
Showing
3 changed files
with
52 additions
and
33 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
using System; | ||
using System.Collections.Concurrent; | ||
using System.Collections.Generic; | ||
using System.Globalization; | ||
using System.Linq; | ||
|
||
namespace ReactNative.Reflection | ||
{ | ||
static class EnumHelpers | ||
{ | ||
private static readonly ConcurrentDictionary<Type, IReadOnlyDictionary<string, object>> s_enumCache = | ||
new ConcurrentDictionary<Type, IReadOnlyDictionary<string, object>>(); | ||
|
||
public static T Parse<T>(string value) | ||
{ | ||
var lookup = s_enumCache.GetOrAdd( | ||
typeof(T), | ||
type => Enum.GetValues(type) | ||
.Cast<object>() | ||
.ToDictionary( | ||
e => Normalize(e.ToString()), | ||
e => e)); | ||
|
||
var result = default(object); | ||
if (!lookup.TryGetValue(Normalize(value), out result)) | ||
{ | ||
throw new ArgumentOutOfRangeException( | ||
nameof(value), | ||
string.Format( | ||
CultureInfo.InvariantCulture, | ||
"Invalid value '{0}' for type '{1}'.", | ||
value, | ||
typeof(T))); | ||
} | ||
|
||
return (T)result; | ||
} | ||
|
||
private static string Normalize(string value) | ||
{ | ||
return value.ToLowerInvariant().Replace("-", ""); | ||
} | ||
} | ||
} |
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