Enum value as hidden in C#

后端 未结 9 892
暖寄归人
暖寄归人 2020-12-21 01:40

I have an enum and i want to \"hide\" one of its values (as i add it for future support). The code is written in C#.

public enum MyEnum
{
   ValueA = 0,

            


        
9条回答
  •  抹茶落季
    2020-12-21 02:39

    If you don't want to show it, then don't include it:

    public enum MyEnum
    {
        ValueA = 0,
        ValueB = 1,
    }
    

    Note that a user of this enum can still assign any integer value to a variable declared as MyEnum:

    MyEnum e = (MyEnum)2;  // works!
    

    This means that a method that accepts an enum should always validate this input before using it:

    void DoIt(MyEnum e)
    {
        if (e != MyEnum.ValueA && e != MyEnum.ValueB)
        {
            throw new ArgumentException();
        }
    
        // ...
    }
    

    So, just add your value later, when you need it, and modify your methods to accept it then.

提交回复
热议问题