Enum value as hidden in C#

后端 未结 9 842
暖寄归人
暖寄归人 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:37

    You can't hide it, but you can add a comment that this value doesn't have any effect at this moment. Otherwise just remove it and add it if you add the support, this shouldn't break any other code dependent on it, as long as the original values don't change.

    0 讨论(0)
  • 2020-12-21 02:38

    You could use the 'Obsolete' attribute - semantically incorrect, but it will do what you want:

    public enum MyEnum 
    { 
      ValueA = 0, 
      ValueB = 1, 
      [Obsolete("Do not use this", true)]
      Reserved 
    }
    

    Anyone who tries to compile using the Foo.Reserved item will get an error

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题