约束枚举类型位数 [英] Constraint enum type bit number

查看:103
本文介绍了约束枚举类型位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,

如何约束枚举的位数?

例如,如果4位(不大于0x0f)是下面的DeviceClass的约束。

For example, if 4-bit(not greater than 0x0f) is constraint for DeviceClass below.

谢谢和最好的问候,

E-John

    public enum DeviceClass
    {
        TV = (0x00),
        DVD = (0x01),
        AMP = (0x02),
    }




推荐答案

枚举不是为约束值而设计的。事实上,他们不能这样做。任何整数值都可以映射到任何枚举类型,你无能为力。

Enums are not designed to constraint values. They can't, in fact, do that. Any integral value can be mapped to any enum type and there is nothing you can do about it.

枚举的目的是使提供定义明确的值更容易。使代码更易于编写和读取是一种方便,但实际上并不提供任何额外的安全性。任何依赖于枚举的代码都应该始终验证提供的值
是否有意义。要做到这一点,你可以采取几种方式。正确的方法是查找您支持的特定值。例如,如果您的实现仅支持前2个值,那么您应该明确检查它们。

The purpose of an enum is to make it easier to provide well-defined values. It is a convenience to make code easier to write and read but in fact doesn't provide any additional security. Any code that relies on an enum should always validate the values provided make sense. To do that you can go a couple of ways. The correct way is to look for the specific values you support. For example if your implementation only supports the first 2 values then you should explicitly check for them.

void Foo ( DeviceClass device )
{
   if (device != DeviceClass.TV && device != DeviceClass.DVD)
      throw new ArgumentOutOfRangeException("Bad device");
}

另一种方法是使用
Enum.IsDefined
。此方法采用值和枚举类型并验证值是否在那里。这种方法的问题在于定义值并不意味着您的代码理解它。最常见的例子是当您针对枚举编写
代码,然后将新值添加到枚举中。如果您的代码使用switch / if / etc来标识值,那么该值现在是枚举的一部分这一事实并不会改变您的代码不支持它的事实。因此,只有在实际上并不关心枚举值时才使用
IsDefined。

Another approach is to use Enum.IsDefined. This methods takes a value and an enum type and verifies the value is in there. The problem with this approach is that having the value defined doesn't mean your code understands it. The most common example of this is when you write your code against an enum and then later a new value is added to the enumeration. If your code is using a switch/if/etc to identify the value then the fact that the value is now part of the enum doesn't change the fact that your code doesn't support it. So use IsDefined only when you don't actually care about the enum value.


这篇关于约束枚举类型位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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