Enum value as hidden in C#

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

    This is not possible in C#. All enum values are accessible if the Enum itself is accessible.

    The only way you could simulate accomplishing this is by using a less accessible static field that used an integer value not already used in the Enum.

    public enum MyEnum {
      ValueA = 0;
      ValueB = 1;
    }
    
    internal static class MyEnumEx {
      internal static MyEnum Reserved = (MyEnum)42;
    }
    

    I'm curious though as to why you would want to do this. No matter what you do users can still provide the Reserved value. All that needs to be done is to cast an int of the appropriate value to the MyEnum type.

    // Code that shouldn't access Reserve
    MyEnum reserved = (MyEnum)42;  // Woot!
    

提交回复
热议问题