首页 > 解决方案 > 将类名解析为类型加速器名称

问题描述

我偶然发现了如何使用 一致地获取类的类型加速器名称(即短名称)"$(...)",例如:

PS H:\> "$([System.DirectoryServices.DirectorySearcher])"
adsisearcher
PS H:\> "$([adsisearcher])"
adsisearcher
PS H:\> "$([type]'System.DirectoryServices.DirectorySearcher')"
adsisearcher
PS H:\> "$([type]'adsisearcher')"
adsisearcher

或者,如果您有该类的实例:

PS H:\> "$(([System.DirectoryServices.DirectorySearcher]'').GetType())"
adsisearcher
PS H:\> "$(([adsisearcher]'').GetType())"
adsisearcher

但是查看该类的属性(例如[System.DirectoryServices.DirectorySearcher] | fl),我实际上在其中的任何地方都看不到“adsisearcher”。调用ToString()也无济于事,因为您获得了完整的类名:

PS H:\> [System.DirectoryServices.DirectorySearcher].ToString()
System.DirectoryServices.DirectorySearcher
PS H:\> [adsisearcher].ToString()
System.DirectoryServices.DirectorySearcher

谁能解释这"$(...)"实际上是如何解析短名称的?“回报价值”从何而来?

SO上有许多其他答案解释了如何获取类型加速器的完整列表,但我找不到任何解释这种"$(...)"行为的答案。

标签: powershell

解决方案


这不是执行它的$()操作,而是从[type]to的转换[string]

PS H:\> [System.Int32] -as [string]
int

对于代码生成用例,类型名称转换也通过LanguagePrimitives.ConvertTypeNameToPSTypeName()静态方法公开,该方法在给定可解析类型名称的情况下生成有效的类型文字标记:

PS H:\> [System.Management.Automation.LanguagePrimitives]::ConvertTypeNameToPSTypeName('System.Int32')
[int]
PS H:\> [System.Management.Automation.LanguagePrimitives]::ConvertTypeNameToPSTypeName('System.DirectoryServices.DirectorySearcher')
[adsisearcher]

但是查看该类的属性(例如[System.DirectoryServices.DirectorySearcher] | fl),我实际上在其中的任何地方都看不到“adsisearcher”。

这是因为类型加速器是 PowerShell在底层 (.NET) 类型系统之上强加的类型名称别名——目标类型本身对“类型加速器”是什么一无所知。

内置类型加速器名称的真正“起源”是PowerShell 语言引擎中类型映射的硬编码列表


推荐阅读