关于Enums的简单问题

时间:2011-03-24 23:51:47

标签: c# enums new-operator

internal enum eCoinType 
{
    g = 0,
    h = 1,
    s = 2
}

我在同一段代码中看过这一行:

eCoinType coin = new eCoinType();  

这是什么意思?
Enum的“新”声明有什么作用? 感谢

3 个答案:

答案 0 :(得分:6)

它创建一个eCoinType实例,其默认值为0,对应eCoinType.g。默认构造函数是System.Enum class

的构造函数

请注意,虽然使用了关键字new,但您仍然会创建值类型的项,因为枚举是值类型,而不是引用类型。它与使用new创建结构实例类似。

答案 1 :(得分:1)

只是要添加@BoltClock所说的内容,它将使用默认值创建eCoinType,对于enum派生自的// These all mean the same thing eCoinType coin = eCoinType.g; // <-- This one is preferred, though eCoinType coin = new eCoinType(); eCoinType coin = default(eCointType); eCoinType coin = (eCoinType)0; 数字类型,该值为0。所以它等同于:

{{1}}

答案 2 :(得分:0)

这是一种不好的态度。我有程序员使用这个默认构造函数来枚举,它基本上分配了枚举的第一个值,而程序员实际上需要枚举的第一个值。请注意,有些人在现有枚举中添加值而不关心顺序,如果他们将新值放在顶部,则会在代码编写的代码中得到未定义的行为。

eCoinType cointype = new eCoinType();

在这种情况下等于

eCoinType cointype = eCoinType.g;

但是如果你修改eCoinType并在g之前加上一些东西,你就改变了应用程序逻辑。

Mybe有一个用例(通过使用在不同的插件模块中声明的枚举来修改应用程序逻辑吗?)但是这与Visual Basic中的Shadows overloading关键字一样多:)