gpt4 book ai didi

.net - 在Powershell中动态检索类信息

转载 作者:行者123 更新时间:2023-12-02 18:40:59 26 4
gpt4 key购买 nike

所以问题相当简单,但我不知道如何措辞才能找到答案。

我正在尝试访问一个类,即 [MyCustomClass] 以检查静态属性,但我需要动态执行此操作。如何注入(inject)类名,例如 [$className]

或者是否有任何 cmdlet 或 .NET 类函数可以用于此目的?我尝试搜索 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
  • 使用 -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

    静态成员运算符 :: 也适用于实例引用,因此如果您有一个 [MyCustomClass] 类型的对象,请使用它代替类型文字:

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

    关于.net - 在Powershell中动态检索类信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68025616/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com