2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

カスタム Enum.TryParse

Posted at

基になる数値の文字列表現はパースできません。

速度については、これまた測定していません。

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;
    }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?