基になる数値の文字列表現はパースできません。
速度については、これまた測定していません。
EnumHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var enumType = typeof(FooBar);
var helper = (EnumHelperBase)Activator.CreateInstance(typeof(EnumHelper<>).MakeGenericType(enumType));
TestParse(helper, "");
TestParse(helper, "Default");
TestParse(helper, "Foo");
TestParse(helper, "Bar");
TestParse(helper, "Baz");
TestParse(helper, "Fizz");
TestParse(helper, "Buzz");
TestParse(helper, "FizzBuzz");
}
private static void TestParse(EnumHelperBase helper, string value)
{
object result;
bool success = helper.TryParse(value, out result);
Console.WriteLine("Success={0}, Result={1}", success, result);
}
}
public enum FooBar
{
Default = 0,
Foo = 0,
Bar = 3,
Baz = 6,
Fizz = 3,
Buzz = 5,
FizzBuzz = 15,
}
public abstract class EnumHelperBase
{
public abstract bool TryParse(string value, out object result);
}
public class EnumHelper<T> : EnumHelperBase where T : struct
{
private readonly Dictionary<string, T> table;
public EnumHelper()
{
Type t = typeof(T);
if (!t.IsEnum)
{
throw new InvalidOperationException("Type parameter is not enum.");
}
var fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
table = fields.ToDictionary(x => x.Name, x => (T)x.GetRawConstantValue());
}
public bool TryParse(string value, out T result)
{
return table.TryGetValue(value, out result);
}
public override bool TryParse(string value, out object result)
{
T enumResult;
bool success = this.TryParse(value, out enumResult);
result = enumResult;
return success;
}
}