C# 枚举数组接受错误值

发布于 2024-12-01 08:06:02 字数 914 浏览 3 评论 0原文

我正在开发一个 Web 服务方法,该方法将接收一个整数数组作为参数,然后在该方法内,我将数组中的值转换为枚举值,并将它们存储在枚举列表中。但是,当传递不在枚举中的值时,它会毫无问题地添加到枚举列表中。没有InvalidCastException,什么也没有。我制作了一个如下所示的测试项目:

static class Program
{
    static void Main(string[] args)
    {
        List<TestValues> values = new List<TestValues>() {
            TestValues.Value1,
            TestValues.Value2,
            (TestValues)15
        };

        foreach (var val in values)
            Console.WriteLine(val);

        Console.Read();
    }

    enum TestValues
    { 
        Value1 = 2,
        Value2 = 4,
        Value3 = 8
    }
}

当我运行它时,输出为:

Value1
Value2
15

对于我的 Web 服务,我将实现验证,因此这种情况根本不会发生。但是……这很奇怪!运行时不应该抛出 InvalidCastExceptionArgumentOutOfRangeException 或类似的东西吗?由于我得到了枚举列表(而不是 int 值),因此我希望这些值仅限于枚举的值(这就是枚举的用途)。

我错过了什么吗?这是 .NET 错误、C# 错误还是有一些我不知道的枚举?

I was working on a web service method that will receive an array of ints as parameter, and then, inside the method, I converted the values in the array into enum values, and stored them in a enum list. However, when a value that's not in the enum is passed, it is added to the enum list with no problems. No InvalidCastException, nothing. I made a test project that looks like this:

static class Program
{
    static void Main(string[] args)
    {
        List<TestValues> values = new List<TestValues>() {
            TestValues.Value1,
            TestValues.Value2,
            (TestValues)15
        };

        foreach (var val in values)
            Console.WriteLine(val);

        Console.Read();
    }

    enum TestValues
    { 
        Value1 = 2,
        Value2 = 4,
        Value3 = 8
    }
}

When I run it, the output is:

Value1
Value2
15

For my web service, I'll implement a validation, so this will never hapen at all. But... this is weird! Shouldn't the runtime throw a InvalidCastException or ArgumentOutOfRangeException, or something similar? Since I got a list of enums (and not int values), I want the values to be limitted to the values of the enum (that's what an enum is for).

Am I missing something? Is this a .NET bug, a C# bug or is there something I don't know with enums?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

零度° 2024-12-08 08:06:02

您可以将基础类型允许的任何值分配给enum。默认情况下,基础类型为 int,因此您可以将任何 int 值分配给 enum

这样做的主要原因是,如果您有一个 [Flags] 枚举,您希望能够分配复合值:

[Flags]
public enum MyFlags
{
    A = 1,
    B = 2
}

MyFlags flags = (MyFlags)3; // Equivalent to setting A and B

最好只使用枚举值来不过,请这样做:

MyFlags flags = MyFlags.A | MyFlags.B; // Sets flags to 3

当然,需要注意的是,启用此分配不需要 [Flags] 属性。根据设计,所有enum都具有此属性。

正如许多人所指出的,您可以使用 Enum.IsDefined() 来确定特定值对于给定的枚举是否有效。这应该有助于您的验证。

You can assign any value to an enum that the underlying type allows. By default, the underlying type is int, so you can assign any int value to the enum.

The main reason for this is because if you have a [Flags] enumeration, you want to be able to assign composite values:

[Flags]
public enum MyFlags
{
    A = 1,
    B = 2
}

MyFlags flags = (MyFlags)3; // Equivalent to setting A and B

Preferably you'd just use the enumeration values to do that, though:

MyFlags flags = MyFlags.A | MyFlags.B; // Sets flags to 3

It's important to note, of course, that the [Flags] attribute isn't required to enable this assignment. All enums have this property, by design.

As pointed out by a number of people, you can use Enum.IsDefined() to determine if a particular value is valid for a given enum. That should help with your validation.

手心的海 2024-12-08 08:06:02

是的,转换为枚举值时不会检查定义的值。

您可以使用 IsDefined 方法来检查是否定义了特定值:

if (Enum.IsDefined(typeof(TestValues), value)) ...

Yes, there is no check for defined values when you convert to an enum value.

You can use the IsDefined method to check if a specific value is defined:

if (Enum.IsDefined(typeof(TestValues), value)) ...
活雷疯 2024-12-08 08:06:02

您始终可以将任何 int 值转换为基于 int 的枚举。这是设计使然,因为如果必须检查所有合法值,转换速度会慢很多。

You can always cast any int value to an enum based on int. This is by design, as the cast would be a lot slower if it had to check all legal values.

旧故 2024-12-08 08:06:02

您应该阅读以下主题:

为什么 Enum.Parse 创建未定义的条目?

简而言之,这是有效的。如果您想检查该值是否已定义,请使用Enum.IsDefined

You should read the following thread:

Why does Enum.Parse create undefined entries?

In short, this is valid. If you want to check if the value is defined, use Enum.IsDefined.

陌生 2024-12-08 08:06:02

要确定指定的 int 是否在 enum 中定义,您可以使用 Enum.IsDefined

Enum.IsDefined(typeof(TestValues), 15);

To determine if the specified int is defined within the enum you can use Enum.IsDefined.

Enum.IsDefined(typeof(TestValues), 15);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文