相关疑难解决方法(0)

PowerShell类型加速器:PSObject vs PSCustomObject

在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. 如果加速器做其他东西而不仅仅指向底层类,如何检查,也许使用反射?

powershell pscustomobject psobject powershell-5.0 type-accelerators

13
推荐指数
1
解决办法
5457
查看次数