先看例子:
public enum Color
{
Red,
Blue,
Gray,
}
Color redColorEnum = EnumParser<color>.Parse("Red");
</color>
以下是实现代码:
public static class EnumParser<t>
{
private static readonly Dictionary<string , T> _dictionary = new Dictionary</string><string , T>();
static EnumParser()
{
if (!typeof(T).IsEnum)
throw new NotSupportedException("Type " + typeof(T).FullName + " is not an enum.");
string[] names = Enum.GetNames(typeof(T));
T[] values = (T[]) Enum.GetValues(typeof(T));
int count = names.Length;
for(int i=0; i<count ; i++)
_dictionary.Add(names[i], values[i]);
}
public static bool TryParse(string name, out T value)
{
return _dictionary.TryGetValue(name, out value);
}
public static T Parse(string name)
{
return _dictionary[name];
}
}