PowerShell类型加速器:PSObject vs PSCustomObject

Ada*_*ski 13 powershell pscustomobject psobject powershell-5.0 type-accelerators

在PowerShell v3.0 PSCustomObject中引入了.就像PSObject,但更好.在其他改进中(例如保留属性顺序),简化了从哈希表创建对象:

[PSCustomObject]@{one=1; two=2;}
Run Code Online (Sandbox Code Playgroud)

现在看来这句话很明显:

[System.Management.Automation.PSCustomObject]@{one=1; two=2;}
Run Code Online (Sandbox Code Playgroud)

将以相同的方式工作,因为它PSCustomObject是完整命名空间+类名的"别名".相反,我得到一个错误:

无法将类型"System.Collections.Hashtable"的"System.Collections.Hashtable"价值型"System.Management.Automation.PSCustomObject".

我列出了两种类型对象的加速器:

[accelerators]::get.GetEnumerator() | where key -Like ps*object

    Key            Value
    ---            -----
    psobject       System.Management.Automation.PSObject
    pscustomobject System.Management.Automation.PSObject
Run Code Online (Sandbox Code Playgroud)

并发现它们都引用了同一个PSObject类 - 这意味着使用加速器可以做一些其他的东西,而不仅仅是缩短代码.

我对这个问题的疑问是:

  1. 在使用加速器和使用完整类型名称之间,您是否有一些有趣的差异?
  2. 如果加速器可用作一般最佳实践,是否应避免使用完整类型名称?
  3. 如果加速器做其他东西而不仅仅指向底层类,如何检查,也许使用反射?

mjo*_*nor 6

看一下静态方法:

PS C:\> [PSCustomObject] | gm -Static -MemberType Method



   TypeName: System.Management.Automation.PSObject

Name            MemberType Definition                                                        
----            ---------- ----------                                                        
AsPSObject      Method     static psobject AsPSObject(System.Object obj)                     
Equals          Method     static bool Equals(System.Object objA, System.Object objB)        
new             Method     psobject new(), psobject new(System.Object obj)                   
ReferenceEquals Method     static bool ReferenceEquals(System.Object objA, System.Object o...



PS C:\> [System.Management.Automation.PSCustomObject] | gm -Static -MemberType Method



   TypeName: System.Management.Automation.PSCustomObject

Name            MemberType Definition                                                        
----            ---------- ----------                                                        
Equals          Method     static bool Equals(System.Object objA, System.Object objB)        
ReferenceEquals Method     static bool ReferenceEquals(System.Object objA, System.Object o...
Run Code Online (Sandbox Code Playgroud)

类型加速器添加了几个新的静态方法.我怀疑它正在使用其中一个作为构造函数.