簡體   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