首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我可以用[pscustomobject]而不是[System.Management.Automation.PSCustomObject]?来创建对象?

为什么我可以用[pscustomobject]而不是[System.Management.Automation.PSCustomObject]?来创建对象?
EN

Stack Overflow用户
提问于 2020-04-10 13:28:12
回答 1查看 367关注 0票数 1

为什么我可以用类型加速器pscustomobject而不是它的全名System.Management.Automation.PSCustomObject创建对象呢?有什么神奇的构造函数我没有访问吗?

代码语言:javascript
复制
$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,但我只得到了一个哈希表:

代码语言:javascript
复制
[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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-10 13:41:01

,我没有访问什么神奇的构造函数吗?

不,编译器中有魔力--每当PowerShell编译器看到一个转换表达式,其中右边是字典,类型为pscustomobject时,它就会将字典或哈希表(无论是字面还是非文本)视为有序字典,并将其转换为PSObject

来自VisitConvertExpression in Compiler.cs

代码语言:javascript
复制
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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61141308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档