0
1

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 3 years have passed since last update.

enum のDisplayName が指定した文字列と一致するか調べる拡張メソッド

Posted at

flags でないなら単純に指定されたenum値のDisplayName と文字列を比較すれば良いけどflags だと タイプ1,タイプ2、合成値 みたいな定義になってタイプ1かタイプ2のどちらかでよい場合、って言う比較があると便利かも、と思った

こんな感じでどうだろう

    [Flags]
    public enum SampleTypes
    {
        [Display(Name = "flag none")]
        None = 0,
        [Display(Name = "flag 1")]
        Flag1 = 1,
        [Display(Name = "flag 2")]
        Flag2 = 2,
        [Display(Name = "flag 3")]
        Flag3 = 3,
        [Display(Name = "flag 4")]
        Flag4 = 4,
        [Display(Name = "flag all")]
        FlagAll = 7
    }
    class Program
    {
        static void Main(string[] args)
        {
            var flag = SampleTypes.Flag3;
            // Your code here!

            System.Console.WriteLine(flag == SampleTypes.Flag3);
            System.Console.WriteLine(flag.DisplayNameMatches("flag all"));
            Console.ReadLine();
        }
    }

    public static class EnumExtension
    {
        public static string DisplayName(this Enum value)
        {
            var enumType = value.GetType();
            var memberInfo = enumType.GetMember(value.ToString()).First();
            if (memberInfo == null || !memberInfo.CustomAttributes.Any())
            {
                return value.ToString();
            }

            var displayAttribute = memberInfo.GetCustomAttribute<DisplayAttribute>();
            if (displayAttribute == null)
            {
                return value.ToString();
            }

            return displayAttribute.Name ?? value.ToString();
        }
        public static bool DisplayNameMatches(this Enum value, string name)
        {
            foreach(var e in Enum.GetValues(value.GetType()))
            {
                var sourceValue = (Enum)e;
                
                if(value.HasFlag((Enum)e))
                {
                    var displayName = DisplayName((Enum)e);
                    if (displayName == name)
                    {
                        return true;
                    }

                }
            }
            return false;
        }
    }

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?