What is the proper name for what [ordered] is in PowerShell 3.0?

对着背影说爱祢 提交于 2019-12-10 15:04:17

问题


In PowerShell, you can specify a type with square brackets like so:

PS C:\Users\zippy> [int]

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

There are also built in type accelerators like [xml] which saves a few keystrokes when you wish to cast something to an XmlDocument.

PS C:\Users\zippy> [xml]

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

You can generate the list via one of the two commands:

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

PowerShell 3.0 adds an operator called [ordered]. Its not a type alias though.

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

However, it can cast Hashtables to OrderedDictionarys.

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

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

So my question is, if [ordered] is not a type accelerator, what is it?


回答1:


Unfortunately [ordered] is a bit of an aberration. It's neither a type nor an accelerator. It only exists in the parser and is treated as a hint on how to create a hashtable (i.e. don't use hashtable, use ordereddictionary instead.) Think of it as a .net attribute, except it's not :D




回答2:


Using the following command :

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

Let me imagine that the interpreter try to match recursively type in loaded assemblies and finished to match OrderedDictionary, this is just a supposition.



来源:https://stackoverflow.com/questions/10238698/what-is-the-proper-name-for-what-ordered-is-in-powershell-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!