非唯一枚举值 [英] Non-unique enum values

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

问题描述

我试图掩盖上的电子数据交换文件的索引位置......我有一种情况,2或3事情可能会根据情况的指数。这将会是很酷用枚举隐藏幻数,并惊讶地看到,你可以指定多个枚举像这样相同的值:

I am trying to obscure the index positions on an edi file... I had a situation where 2 or 3 things could be at an index based on the situation. It'd be cool to use an enum to hide the "magic numbers" and was suprised to see that you could assign multiple enums to the same value like this:

public enum Color
{
    Red = 1,
    Blue = 1,
    Green = 1
}

和编译器很高兴与此有关。我没想到这个工作。我并不需要转换回枚举,所以我并不担心想回去,但是这的气味的时髦。为什么CLR允许枚举多个值,我应该使用结构为这个? (A结构似乎更重的责任不是一个枚举,这似乎工作)

and the compiler is happy with this. I didn't expect this to work. I don't need to cast back to the enum so I'm not worried about trying to go back, but this smells funky. Why does the CLR allow multiple values for enums and should I use a struct for this? (A struct seemed heavier duty than an enum and this seems to work)

推荐答案

其实已经傻冒定义结构......幕后枚举只是一个结构(但是从System.Enum派生)和值枚举被定义为常数(你可以用ILDASM验证)。

Actually your'e already defining a struct... Behind the scenes an enum is just a struct (but which derives from System.Enum) and the values of the enum are defined as constants (you can verify this with ILDASM).

您枚举定义转换为以下伪C#code:

Your enum definition translates into the following pseudo C# code:

public struct Color : System.Enum
{
    public const int Red = 1;
    public const int Blue = 1;
    public const int Green = 1;
}

以上code不会在C#编译,因为编译器不允许定义具有明确的基类的一个结构,但是这就是它发出了一个枚举的定义。

The above code won't compile in C# because the compiler doesn't allow defining a struct with an explicit base class, but that's what it emits for an enum definition.

由于存在与包含具有相同值的多个常数型没有问题的,存在与枚举定义没有问题。

Since there is no problem with a type that contains an multiple constants that have the same value, there is no problem with the enum definition.

但由于枚举不具有唯一值转换为枚举时,你可能有一个问题。
例如下面的两个线路的codeS将返回枚举值红色,因为第一个值被任意地选择。

But since the enum does not have unique values you might have an issue when converting into this enum. For example the following two line of codes will return the enum value Red, because the first value is arbitrarily selected.

Color color1 = (Color)1;
Color color2 = (Color)Enum.Parse(typeof(Color), "1");

严格地说枚举值不红,那是1,但是当你打印出来的价值,你会看到红色。

Strictly speaking the enum value is not Red, it is 1, but when you print out the value you'll see Red.

此外,下面的布尔是真实的,看起来有点怪......

Also, the following boolean is true which looks a bit weird...

// true (Red is Green??)
bool b = Color.Red == Color.Green;

目前的底线,这是完全合法的,但它给你当它是有道理的使用它...

At the bottom line this is perfectly legal, but it's up to you to use it when it makes sense...

下面是直接链接到我的.NET教程的发动机罩下的讨论枚举的部分: http://motti.me/c1E

Here is a direct link to the section of my .NET tutorial that discusses enumerations under the hood: http://motti.me/c1E

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

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