【发布时间】:2016-06-23 23:39:55
【问题描述】:
在 PowerShell v3.0 中引入了PSCustomObject。就像PSObject,但更好。在其他改进中(例如保留属性顺序),从哈希表创建对象得到了简化:
[PSCustomObject]@{one=1; two=2;}
现在看来,这句话很明显:
[System.Management.Automation.PSCustomObject]@{one=1; two=2;}
会以同样的方式工作,因为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
并发现两者都引用了相同的 PSObject 类 - 这意味着使用加速器可以做很多其他事情,而不仅仅是缩短代码。
我关于这个问题的问题是:
- 您有一些有趣的例子来说明使用加速器与使用完整类型名称之间的区别吗?
- 作为一般最佳实践,只要有加速器可用,是否应避免使用完整类型名称?
- 如何检查(可能使用反射)加速器是否执行其他操作而不只是指向底层类?
【问题讨论】:
-
如果你反编译
System.Management.Automation.Language.Compiler.VisitConvertExpression,那么你可以看到对ordered、PSCustomObject和ref这三个类型名称有特殊处理。
标签: powershell powershell-5.0 psobject pscustomobject type-accelerators