【问题标题】:What is the proper name for what [ordered] is in PowerShell 3.0?PowerShell 3.0 中 [ordered] 的正确名称是什么?
【发布时间】:2012-04-20 00:27:42
【问题描述】:

在 PowerShell 中,您可以使用方括号指定类型,如下所示:

PS C:\Users\zippy> [int]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

还有像 [xml] 这样的内置类型加速器,当您希望将某些内容投射到 XmlDocument 时,它可以节省一些击键。

PS C:\Users\zippy> [xml]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    XmlDocument                              System.Xml.XmlNode

您可以通过以下两个命令之一生成列表:

  • PS v2.0 [type]::gettype("System.Management.Automation.TypeAccelerators")::Get
  • PS v3.0 [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")::Get

PowerShell 3.0 添加了一个名为 [ordered] 的运算符。虽然它不是类型别名。

PS C:\Users\zippy> [ordered]
Unable to find type [ordered]: make sure that the assembly containing this type is loaded.
At line:1 char:1
+ [ordered]
+ ~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (ordered:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

但是,它可以将Hashtables 转换为OrderedDictionarys。

PS C:\Users\zippy> ([ordered]@{}).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     OrderedDictionary                        System.Object

所以我的问题是,如果 [ordered] 不是类型加速器,它是什么?

【问题讨论】:

    标签: powershell-3.0


    【解决方案1】:

    不幸的是[ordered] 有点失常。它既不是类型也不是加速器。它只存在于解析器中,并被视为有关如何创建哈希表的提示(即不要使用哈希表,而是使用有序字典。)将其视为 .net 属性,但它不是:D

    【讨论】:

    • 实际上,我称之为类型别名。
    • @TaylorGibb 看看我的问题,我通过展示如何枚举所有类型别名来证明它不是类型别名。
    【解决方案2】:

    使用以下命令:

    Trace-Command -Name TypeConversion -Expression {([ordered]@{}).gettype()} -PSHost
    

    让我想象一下解释器尝试递归匹配加载的程序集并完成匹配OrderedDictionary,这只是一个假设。

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      相关资源
      最近更新 更多