Enumerations

Enumeration Syntax and Semantics

Slice 枚举类型定义看起来与 C++ 相同:

1
2
3
4
module M
{
enum Fruit { Apple, Pear, Orange }
}

This definition introduces a type named Fruit that becomes a new type in its own right. Slice guarantees that the values of enumerators increase from left to right, so Apple compares less than Pear in every language mapping. By default, the first enumerator has a value of zero, with sequentially increasing values for subsequent enumerators.

A Slice enum type introduces a new namespace scope, so the following is legal:

这个定义引入了一个名为 Fruit 的类型,它本身就成为一种新类型。 Slice 保证枚举数的值从左到右递增,因此 Apple 在每种语言映射中都比 Pear 进行比较。 默认情况下,第一个枚举数的值为零,后续枚举数的值依次增加。

Slice 枚举类型引入了新的命名空间范围,因此以下内容是合法的:

1
2
3
4
5
module M
{
enum Fruit { Apple, Pear, Orange }
enum ComputerBrands { Apple, Dell, HP, Lenovo }
}

The example below shows how to refer to an enumerator from a different scope:

下面的示例展示了如何从不同的范围引用枚举:

1
2
3
4
5
6
7
8
9
10
11
module M
{
enum Color { Red, Green, Blue }
}
module N
{
struct Pixel
{
M::Color c = Blue;
}
}

Slice does not permit empty enumerations.

Slice 不允许空枚举。

In Ice releases prior to Ice 3.7, an enum type did not create a new namespace and its enumerators were in the same namespace as the enum type itself. With these releases, you had to select longer enumerator names to avoid a naming clash.

在 Ice 3.7 之前的 Ice 版本中,枚举类型不会创建新的命名空间,并且其枚举器与枚举类型本身位于同一命名空间中。 在这些版本中,您必须选择更长的枚举器名称以避免命名冲突。

Custom Enumerator Values

Slice also permits you to assign custom values to enumerators:

Slice 还允许您为枚举器分配自定义值:

1
2
const int PearValue = 7;
enum Fruit { Apple = 0, Pear = PearValue, Orange }

Custom values must be unique and non-negative, and may refer to Slice constants of integer types. If no custom value is specified for an enumerator, its value is one greater than the enumerator that immediately precedes it. In the example above, Orange has the value 8.

The maximum value for an enumerator value is the same as the maximum value for int, 2 31 - 1.

Slice does not require custom enumerator values to be declared in increasing order:

自定义值必须是唯一且非负的,并且可以引用整数类型的 Slice 常量。 如果没有为枚举器指定自定义值,则其值比紧邻其前面的枚举器大 1。 在上面的示例中,Orange的值为 8。

枚举值的最大值与 int 的最大值相同,即 2^31 - 1。

Slice 不需要按升序声明自定义枚举值:

1
enum Fruit { Apple = 5, Pear = 3, Orange = 1 }   // 合法的

Note however that when there is an inconsistency between the declaration order and the numerical order of the enumerators, the behavior of comparison operations may vary between language mappings.

但请注意,当声明顺序与枚举数的数字顺序不一致时,比较操作的行为可能会因语言映射而异。

For an application that is still using version 1.0 of the Ice encoding, changing the definition of an enumerated type may break backward compatibility with existing applications. For more information, please refer to the encoding rules for enumerators.

对于仍在使用 Ice 编码 1.0 版的应用程序,更改枚举类型的定义可能会破坏与现有应用程序的向后兼容性。 更多信息请参考枚举数的编码规则。