枚举值隐藏在C#中 [英] Enum value as hidden in C#

查看:175
本文介绍了枚举值隐藏在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举,我想隐藏它的一个值(因为我添加了它以便将来支持)。
代码用C#编写。

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,

   ValueB = 1,

   Reserved
}

我不想允许使用此代码的人使用此值(MyEnum.Reserved)。
有什么想法吗?
TIA

I don't want to allow peoples who use this code to use this values (MyEnum.Reserved). Any idea? TIA

推荐答案

如果不想显示它,则不要包含它:

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

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

请注意,此枚举的用户仍可以将任何整数值分配给声明为MyEnum的变量: / p>

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.

这篇关于枚举值隐藏在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆