.NET:为什么不检查Enum的范围/值? [英] .NET: Why aren't Enum's Range/Value Checked?

查看:78
本文介绍了.NET:为什么不检查Enum的范围/值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一直困扰着我。也许对.NET内部有一定了解的人可以向我解释。

This has always bugged me. Perhaps someone with some hardcore knowledge of .NET internals can explain it to me.

假设我将枚举定义如下:

Suppose I define an enum as follows:

public enum Foo
{
   Eenie = 1,
   Meenie = 2,
   Miney = 3,
   Moe = 4
}

现在,还假设我的代码中有以下内容代码:

Now, also suppose that somewhere in my code, I have the following code:

int bar = (Foo)5;

这将编译得很好,并且即使值5明显也不会引发任何异常不是在 Foo 中定义的有效值。

This will compile just fine, and no exception will be raised whatsoever, even though the value 5 is clearly not a valid value defined in Foo.

或者,请考虑以下内容:

Or, consider the following:

public void ProcessFoo(Foo theFoo)
{
    // Do processing
}

public static void Main()
{
    ProcessFoo((Foo)5);
}

同样,也不例外。

在我看来,这将导致类型不匹配异常,因为5不是 Foo 。但是设计师选择不这样做。

In my mind, this should result in a type mismatch exception, because 5 is not a Foo. But the designers chose not to do that.

现在,我编写了一个扩展方法,可以验证是否是这种情况,并且调用它以确保是这种情况没什么大不了的,但是我

Now, I've written an extension method that can verify that this is the case, and it's no big deal to invoke it to ensure that that's the case, but I have to use reflection to do it (with all its performance penalties and whatnot).

因此,再次有什么令人信服的原因可能导致决定放弃一个检查的枚举?

So again, what compelling reason is there that could possibly have driven the decision to not have a checked enum?

作为参考,来自 Enum类的MSDN文档


当您定义一个方法或属性
时,枚举常量为
值,请考虑验证该值。
原因是您可以将
数值转换为枚举类型
,即使该数值不是枚举中定义的

When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.


推荐答案

问题出在性能上。对正常的枚举(例如Color)进行检查的枚举很简单

The issue was performance. It is quite simple to have a checked enum for normal enums such as Color

enum Color {
  Red,
  Blue
}

问题在于使用枚举的位标记。

The problem though is for enum's which are used as bit flags.

enum Property {
  IsFirst = 0x1,
  IsDefault = 0x2,
  IsLastAccessed = 0x4
}

必须对转换为Enum的每个整数进行按位检查价值被认为太昂贵了。因此,轻松地转换为枚举值。

Having to do a bitwise check for every single integer which is converted to an Enum value was deemed to be too expensive. Hence the relaxed conversion to enum values.

这篇关于.NET:为什么不检查Enum的范围/值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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