PowerShell类型转换使用存储在变量中的类型

Tre*_*van 3 .net powershell

我想将.NET对象转换为另一种.NET类型,但是:

  • 目标.NET类型(类)存储在变量中
  • 我不想使用-asPowerShell运算符
  • 我正在使用复杂的非原始类型

你会如何实现这一目标?

例如,这是"PowerShell"的方式,但我不想使用-as:

$TargetType = [System.String]; # The type I want to cast to
1 -as $TargetType;             # Cast object as $TargetType
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用:

$TargetType = [System.String];
[$TargetType]1;
Run Code Online (Sandbox Code Playgroud)

..因为在这种情况下,PowerShell不允许在方括号内使用变量.

我想象的是:

$TargetType = [System.String];
$TargetType.Cast(1); # Does something like this exist in the .NET framework?
Run Code Online (Sandbox Code Playgroud)

可以用.NET方法语法完成吗?有没有静态方法可以做到这一点?

Jas*_*irk 7

您可以使用以下方法粗略模拟强制转换:

[System.Management.Automation.LanguagePrimitives]::ConvertTo($Value, $TargetType)
Run Code Online (Sandbox Code Playgroud)

对于提供自己的转换的动态对象,真正的强制转换可能与上述方法的行为不同.否则,我能想到的唯一其他差异就是性能 - 由于ConvertTo静态方法中没有的优化,真正的强制转换可能会表现得更好.

要精确模拟强制转换,您需要生成一个类似于以下内容的脚本块:

function GenerateCastScriptBlock
{
    param([type]$Type)

    [scriptblock]::Create('param($Value) [{0}]$Value' -f
        [Microsoft.PowerShell.ToStringCodeMethods]::Type($Type))
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将此脚本块分配给函数或直接调用它,例如:

(& (GenerateCastScriptBlock ([int])) "42").GetType()
Run Code Online (Sandbox Code Playgroud)

  • 这是一个非常不同的问题.编程语言定义有效的转换.例如,PowerShell或C++/CLI中的转换可能与C#允许的转换不同.我认为您需要在寻找一个能够满足您需求的简单API之前指定您想要转换的具体内容. (2认同)