繁体   English   中英

动态获取Powershell中的class信息

[英]Dynamically retrieve class information in Powershell

所以这个问题相当简单,但我不确定如何表达才能找到答案。

我正在尝试访问 class 即[MyCustomClass]以检查 static 属性,但我需要动态执行。 如何注入[$className]之类的 class 名称?

或者是否有任何 cmdlet 或 .NET class 函数可以用于此目的? 我尝试搜索Get-Command *Class*和一些类似的命令,但没有找到任何结果。

有 2 个主要选项可用于按名称解析给定类型,每个选项的行为略有不同:

  1. 使用强制转换为[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
  1. 使用-as类型转换运算符(在 PowerShell 3.0 版本中引入):
$myType = 'MyCustomClass' -as [type]

与强制转换不同, -as运算符从不抛出 - 它只是返回$null

PS ~> $myType = 'this does not exist' -as [type]
PS ~> $null -eq $myType
True

这两者的共同点是您现在可以解析[MyCucstomClass]的 static 成员:

$myType::MyProperty

static 成员运算符::也适用于实例引用,因此如果您有类型为[MyCustomClass]的 object,请使用它代替类型文字:

class MyClass
{
  static [string] $StaticValue = 'Static string value'
}
PS ~> $instance = [MyClass]::new()
PS ~> $instance::StaticValue
Static string value

您可以使用Invoke-Expression来运行您仍然需要构建的东西:

$class = 'DateTime'
Invoke-Expression "[$class]::Now"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM