有 2 个主要选项可用于按名称解析给定类型,每个选项的行为略有不同:
- 使用转换为
[type]:
$className = 'MyCustomClass'
$myType = [type]$className
尝试强制转换不存在的类型名称将引发异常:
PS ~> [type]'Not actually a type'
Cannot convert the "Not actually a type" value of type "System.String" to type "System.Type".
At line:1 char:1
+ [type]'Not actually a type'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToType
- 使用
-as 类型转换运算符(在 PowerShell 版本 3.0 中引入):
$myType = 'MyCustomClass' -as [type]
与强制转换不同,-as 运算符 从不 抛出 - 它只是返回 $null:
PS ~> $myType = 'this does not exist' -as [type]
PS ~> $null -eq $myType
True
这两者的共同点是您现在可以解析[MyCucstomClass] 的静态成员:
$myType::MyProperty
静态成员运算符:: 也适用于instance 引用,因此如果您有[MyCustomClass] 类型的对象,请使用它来代替类型文字:
class MyClass
{
static [string] $StaticValue = 'Static string value'
}
PS ~> $instance = [MyClass]::new()
PS ~> $instance::StaticValue
Static string value