首页 > 解决方案 > 将字符串转换为数据类型以存储在哈希表中

问题描述

我的代码中有这样的东西:

 [MVPSI.JAMS.CredentialRights]::Submit

我希望能够抽象它,这样我就可以有效地改变它的一部分,我希望它是一个字符串:

$typeName = "MVPSI.JAMS.CredentialRights"
$function = "Submit"

但是我不能这样做:

$typeName::$function

我该怎么做呢?公平地说,我什至不知道这些是什么特殊的[],并且::在 .Net\PowerShell 中被调用。

标签: powershell

解决方案


我什至不知道这些特殊的 [] 和 :: 在 .Net\PowerShell 中被称为什么

  • [...]分隔类型文字;例如[MVPSI.JAMS.CredentialRights]

  • ::访问类型的静态成员

请注意,这两种语法形式都是特定于PowerShell的。

使用类型文字的替代方法是将类型名称(字符串)转换为[type]

# The type name as a string.
$typeName = 'MVPSI.JAMS.CredentialRights'

# Get a reference to the type by its name.
$type = [type] $typeName

# The name of the static method to call.
$function = 'Submit'

# Call the static method on the type by its name.
# Note: Omitting '()' will output the method *signature*, including
#       its overloads.
$type::$function()

推荐阅读