【问题标题】:Powershell generate System.Type out of String [duplicate]Powershell从字符串中生成System.Type [重复]
【发布时间】:2021-12-18 20:48:40
【问题描述】:

我正在动态生成某种类型的 .net 对象,例如 $MyType=([System.Type]::GetType("System.String") 这适用于标准 .net 对象。

我现在创建了一个这样的自定义类

class InstanceName
{
    [String] hidden $Val
    InstanceName([String]$CVal)
    {
        $this.Val=$CVal
    }
}

这里,这个方法不起作用,因为 powershell 找不到类型。 $MyType=([System.Type]::GetType("InstanceName")

知道如何获得自定义 PS 类的 System.Type 吗?

谢谢!

【问题讨论】:

  • $InstanceName = [InstanceName]
  • 简而言之:如果您提前知道类型名称,请使用 类型文字 ([SomeType])。如果类型名称存储在 string 中,请将其强制转换为 [type][type] 'SomeType'(或使用 'SomeType' -as [type])。有关详细信息,请参阅链接的副本。

标签: .net powershell types reflection


【解决方案1】:

使用-as 类型转换运算符:

$instanceNameType = 'InstanceName' -as [type]

# test the type reference
$instanceNameType::new("")

【讨论】:

  • [type]'InstanceName' 也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多