关于 Enum

简短说明

enum 语句用于声明枚举。 枚举是一种非重复类型,由一组名为枚举器列表的命名标签组成。

详细说明

使用 enum 语句可以创建强类型标签集。 该枚举可以在代码中使用,而不必解析或检查拼写错误。

枚举在内部表示为起始值为零的整数。 列表中的第一个标签被分配值 0。 其余标签分配有连续的数字。

在定义中,可以为 labels 指定任何整数值。 没有分配值的标签采用下一个整数值。

语法(基本)

enum <enum-name> {
    <label> [= <int-value>]
    ...
}

用法示例

以下示例显示了可视为媒体文件的对象枚举。 定义将显式值分配给 musicpicturevideo的基础值。 显式赋值后的标签将立即获得下一个整数值。 可以通过将相同的值分配给另一个标签来创建同义词;请参阅以下各项的构造值: ogg、 、 moggoga、 、 jpegjpgmpg或 、 。 mpeg

enum MediaTypes {
    unknown
    music = 10
    mp3
    aac
    ogg = 15
    oga = 15
    mogg = 15
    picture = 20
    jpg
    jpeg = 21
    png
    video = 40
    mpg
    mpeg = 41
    avi
    m4v
}

GetEnumNames() 方法返回枚举的标签列表。

[MediaTypes].GetEnumNames()
unknown
music
mp3
aac
ogg
oga
mogg
picture
jpg
jpeg
png
video
mpg
mpeg
avi
m4v

GetEnumValues() 方法返回枚举的值列表。

[MediaTypes].GetEnumValues()
unknown
music
mp3
aac
oga
oga
oga
picture
jpeg
jpeg
png
video
mpeg
mpeg
avi
m4v

注意:GetEnumNames() 和 GetEnumValues() 似乎返回相同的结果。 但是,在内部,PowerShell 正在将值更改为标签。 仔细阅读列表,您会注意到 ogamogg 在“获取名称”结果下提到,但在“获取值”jpg下没有提到 、 、 jpegmpgmpeg

[MediaTypes].GetEnumName(15)
oga

[MediaTypes].GetEnumNames() | ForEach-Object {
  "{0,-10} {1}" -f $_,[int]([MediaTypes]::$_)
}
unknown    0
music      10
mp3        11
aac        12
ogg        15
oga        15
mogg       15
picture    20
jpg        21
jpeg       21
png        22
video      40
mpg        41
mpeg       41
avi        42
m4v        43

枚举为标志

枚举可以定义为位标志的集合。 其中,在任何给定点,枚举表示打开的一个或多个标志。

要使作为标志的枚举正常工作,每个标签应具有 2 的幂值。

语法 (flags)

[Flags()] enum <enum-name> {
    <label 0> [= 1]
    <label 1> [= 2]
    <label 2> [= 4]
    <label 3> [= 8]
    ...
}

标志使用示例

在下面的示例中,将创建 FileAttributes 枚举。

[Flags()] enum FileAttributes {
    Archive = 1
    Compressed = 2
    Device = 4
    Directory = 8
    Encrypted = 16
    Hidden = 32
}

[FileAttributes]$file1 = [FileAttributes]::Archive
[FileAttributes]$file1 +=[FileAttributes]::Compressed
[FileAttributes]$file1 +=  [FileAttributes]::Device
"file1 attributes are: $file1"

[FileAttributes]$file2 = [FileAttributes]28 ## => 16 + 8 + 4
"file2 attributes are: $file2"
file1 attributes are: Archive, Compressed, Device
file2 attributes are: Device, Directory, Encrypted

要测试是否设置了 specific,可以使用 binary comparison operator -band。 在此示例中,我们测试值中的 $file2DeviceArchive 属性。

PS > ($file2 -band [FileAttributes]::Device) -eq [FileAttributes]::Device
True

PS > ($file2 -band [FileAttributes]::Archive) -eq [FileAttributes]::Archive
False