为什么我可以用类型加速器pscustomobject而不是它的全名System.Management.Automation.PSCustomObject创建对象呢?有什么神奇的构造函数我没有访问吗?
$a = [pscustomobject]@{name='joe'}
$a.gettype().fullname
System.Management.Automation.PSCustomObject
[System.Management.Automation.PSCustomObject]@{name='joe'}
InvalidArgument: Cannot convert the "System.Collections.Hashtable" value of type "System.Collections.Hashtable" to type "System.Management.Automation.PSCustomObject".或者我可以试试System.Management.Automation.PSObject,但我只得到了一个哈希表:
[psobject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::get.pscustomobject.fullname
System.Management.Automation.PSObject
[System.Management.Automation.PSObject]@{name='joe'}
Name Value
---- -----
name joe受这个线程的启发:https://powershell.org/forums/topic/type-accelerator
发布于 2020-04-10 13:41:01
,我没有访问什么神奇的构造函数吗?
不,编译器中有魔力--每当PowerShell编译器看到一个转换表达式,其中右边是字典,类型为pscustomobject时,它就会将字典或哈希表(无论是字面还是非文本)视为有序字典,并将其转换为PSObject。
来自VisitConvertExpression in Compiler.cs
var typeName = convertExpressionAst.Type.TypeName;
var hashTableAst = convertExpressionAst.Child as HashtableAst;
Expression childExpr = null;
if (hashTableAst != null)
{
var temp = NewTemp(typeof(OrderedDictionary), "orderedDictionary");
if (typeName.FullName.Equals(LanguagePrimitives.OrderedAttribute, StringComparison.OrdinalIgnoreCase))
{
return Expression.Block(
typeof(OrderedDictionary),
new[] { temp },
BuildHashtable(hashTableAst.KeyValuePairs, temp, ordered: true));
}
if (typeName.FullName.Equals("PSCustomObject", StringComparison.OrdinalIgnoreCase))
{
// pure laziness here - we should construct the PSObject directly. Instead, we're relying on the conversion
// to create the PSObject from an OrderedDictionary.
childExpr = Expression.Block(
typeof(OrderedDictionary),
new[] { temp },
BuildHashtable(hashTableAst.KeyValuePairs, temp, ordered: true));
}
}请注意,这也是[ordered]@{Key='Value'}如何产生OrderedDictionary的
https://stackoverflow.com/questions/61141308
复制相似问题