Powershell 的基础使用I 枚举值
Powershell 的基础使用I 枚举值
前言
这里是相关基础知识的枚举篇.
基本设计
语法规则
1 | [[<attribute>]...] enum <enum-name> : <underlying-type-name> { |
.
用例1
另见转换1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21enum DELIVER {
Car
Trunk
Cargo
}
[DELIVER].GetEnumNames()
# Car
# Trunk
# Cargo
[DELIVER].GetEnumName(0) # Car
[DELIVER].GetEnumName(1) # Trunk
[DELIVER].GetEnumName(3) # Null
[DELIVER]::Car # Car
[DELIVER]::Car -eq 0 # True
[DELIVER]::CAR -eq 0 # True
[DELIVER]::Car -eq [DELIVER]::Trunk # False
[int][DELIVER]::Car # 0
[DELIVER]::ToObject([DELIVER], 2) # Cargo
[DELIVER]::Car -eq "Car" # True
[DELIVER]::Car -eq "CAR" # True
[DELIVER]::Car -eq "Ben" # false
用例2
控制控制台输出内容的颜色
关于SGR 关于转义符1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35enum SGR{
Black = 30
Red = 31
Green = 32
Yellow = 33
Blue = 34
Magenta = 35
Cyan = 36
White = 37
BrightBlack = 90
BrightRed = 91
BrightGreen = 92
BrightYellow = 93
BrightBlue = 94
BrightMagenta = 95
BrightCyan = 96
BrightWhite = 97
}
function Format-Text {
param (
[string]$str ,
[SGR]$color = [SGR]::White
)
if (($null -ne $str) -and ("" -ne $str.Trim())) {
Write-Output "`e[$([int]$color)m$str`e[0m"
}
}
Format-Text -str 'Default?'
Format-Text -str 'Blue?' -color ([SGR]::Blue)
Format-Text -str 'Red?' -color RED
Format-Text -str 'Green?' -color 32
Format-Text -color Red
SGR
一些小结
- 对于未定义 int-value 的, 使用 0 基底递增
- 根据下标获取枚举名, 失败时不会抛出错误, 如
[DELIVER].GetEnumName(3)
- 枚举名与值只要对应, 都视为相等, 如
[DELIVER]::Car -eq 0
- 可以强转枚举名到值, 如
[int][DELIVER]::Car
- 对于使用比较运算符的, 会自动强转到对应的类型
- 对于使用比较运算符的, 如果自动强转到对应的类型失败, 不会有错误, 只会输出
false
, 如[DELIVER]::Car -eq "Ben"
- 对于函数接收枚举的, 会自动强转到对应的类型
- 枚举名是大小写无关的
- 使用全限定访问符, 需要用括号, 如
([SGR]::Blue)