【发布时间】:2011-07-22 13:43:25
【问题描述】:
internal enum eCoinType
{
g = 0,
h = 1,
s = 2
}
我在相同的代码中看到了这一行:
eCoinType coin = new eCoinType();
这是什么意思?
枚举中的“新”声明有什么作用?
谢谢
【问题讨论】:
标签: c# enums new-operator
internal enum eCoinType
{
g = 0,
h = 1,
s = 2
}
我在相同的代码中看到了这一行:
eCoinType coin = new eCoinType();
这是什么意思?
枚举中的“新”声明有什么作用?
谢谢
【问题讨论】:
标签: c# enums new-operator
它创建一个默认值为 0 的 eCoinType 实例,对应于 eCoinType.g。默认构造函数是 System.Enum class 的构造函数。
请注意,虽然使用了关键字new,但您仍会创建值类型的项,因为枚举是值类型,而不是引用类型。这类似于使用new 创建结构实例。
【讨论】:
只是添加到@BoltClock 所说的内容,它将创建一个具有默认值的eCoinType,在数字类型的情况下为0,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;
【讨论】:
eCoinType coin = default(eCoinType)。
这是一种不好的态度。我让程序员使用这个默认的枚举构造函数,它基本上分配枚举的第一个值,而程序员实际上需要枚举的类型化第一个值。请注意,有些人向现有枚举添加值而不关心顺序,如果他们将新值放在顶部,那么在这样编写的代码中会出现未定义的行为。
eCoinType cointype = new eCoinType();
在这种情况下等于
eCoinType cointype = eCoinType.g;
但是如果你修改 eCoinType 并在 g 之前添加一些东西,你就改变了应用程序逻辑。
Mybe 有一个用例(通过使用在不同插件模块中声明的枚举来修改应用程序逻辑?)但这与 Visual Basic 中的 Shadows 重载关键字一样晦涩:)
【讨论】: