开发者

How to switch on enum that has repeated values or boolean values, in C#?

Given an enum type:

enum SOMEENUM 
{
   A = true,
   B = false,
   C = true
}

I want to switch on this like:

public void SWITCHON (SOMEENUM sn) 
{
   switch(s)
   {
      case SOMEENMUM.A : xxxxxxxx.......
   }
}

But this doesn't compile; I guess it's using the bool value of the enum.

I want to do switch on Enum 开发者_JAVA技巧as if there is no value assigned to it.


First of all:
Enums in C# do not support bool as value. So It should be integers. If we set 2 property's of enum to the same value we can consider one of them lost. From my understanding what you actually is trying to do is: Somehow flag that 2 property's of enum are equal.
My suggestion:

public enum MyEnum
{
    [Description("true")]
    A = 1,
    [Description("false")]
    B = 2,
    [Description("true")]
    C = 3
}

Extension for Enum which will return bool

 public static class EnumEx
    {
        public static bool GetDescriptionAsBool(this Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute attribute
                    = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                        as DescriptionAttribute;
            if(attribute == null)
            {
                //throw new SomethingWentWrongException();
            }
            return bool.Parse(attribute.Description);
        }
    }

As a result you can switch normally and at any time can check what is your enums boll flag just calling GetDescriptionAsBool method of that instance.


Repeated values are just different names for the same thing. There's no way to tell the difference because enums are stored as the values, not as the names.

As for bool values, you use an if for those instead of a switch.


enums require numerical values but do not have to be set. I suggest just removing leaving it like

enum SOMEENUM 
{ 
   A, 
   B,
   C
}

so

public void SWITCHON (SOMEENUM s) 
{
    switch(s) 
    { 
        case SOMEENMUM.A : ...do stuff...
             break;
        case SOMEENMUM.B : ...do stuff...
             break;
        case SOMEENMUM.c : ...do stuff...
             break;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜