【问题标题】:Iterate over static properties of a class迭代类的静态属性
【发布时间】:2016-06-18 18:33:14
【问题描述】:

要访问静态方法,我们使用

[namespace.ClassName]::MethodName()

对于静态属性,我们使用

[namespace.ClassName]::Property

如何遍历这个类中的所有静态属性?

$list = [namespace.ClassName] | Get-Member -Static -MemberType Property

返回所有静态属性的列表,但如何使用它,即访问它的值。 如果我想将变量传递给方法,我该怎么做? $list[0] 不起作用。

【问题讨论】:

    标签: c# .net powershell powershell-4.0 powershell-ise


    【解决方案1】:

    这应该适用于 Name 属性上的 foreach 循环。

    $class = [namespace.ClassName] 
    $list = $class | Get-Member -Static -MemberType Property
    $list | select -expand Name | foreach {
       "$_ = $($class::$_)"
    }
    

    请注意,如果需要,您可以通过更改 $class 变量来迭代类。

    [Math] 类为例:

    PS> $class = [math]
    PS> $class | Get-Member -Static -MemberType Property | select -expand Name | foreach { "$_ = $($class::$_)" }
    E = 2.71828182845905
    PI = 3.14159265358979
    

    【讨论】:

    • 谢谢@RyanBernrose
    【解决方案2】:

    这与 Ryan Bemrose 的答案基本相同,但写成一个吐出对象的函数。

    function Get-StaticProperties
    {
        Param (
            [type]$Class
        )
    
        gm -InputObject $Class -Static -MemberType Property |
            select -ExpandProperty Name | foreach {
                New-Object PSObject -Property ([ordered]@{ Name=$_; Value=$Class::$_ })
            }
    }
    

    然后,调用它:

    PS> Get-StaticProperties System.Math
    
    Name            Value
    ----            -----
    E    2.71828182845905
    PI   3.14159265358979
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2011-06-11
      • 2014-09-10
      • 2011-07-29
      相关资源
      最近更新 更多