我想将 .NET 对象转换为另一种 .NET 类型,但是:
-as
PowerShell 运算符(operator) 你将如何实现这一目标?
例如,这是执行此操作的“PowerShell”方式,但我不想使用
-as
:$TargetType = [System.String]; # The type I want to cast to
1 -as $TargetType; # Cast object as $TargetType
不幸的是,这不起作用:
$TargetType = [System.String];
[$TargetType]1;
.. 因为在这种情况下,PowerShell 不允许在方括号内使用变量。
我在想象这样的事情:
$TargetType = [System.String];
$TargetType.Cast(1); # Does something like this exist in the .NET framework?
可以用 .NET 方法语法来完成吗?有没有静态方法可以做到这一点?
最佳答案
您可以使用以下方法大致模拟类型转换:
[System.Management.Automation.LanguagePrimitives]::ConvertTo($Value, $TargetType)
对于提供自己转换的动态对象,真正的强制转换的行为可能与上述方法不同。否则,我能想到的唯一其他区别是性能 - 由于 ConvertTo 静态方法中不可用的优化,真正的强制转换可能会表现得更好。
要精确模拟类型转换,您需要生成一个包含以下内容的脚本块:
function GenerateCastScriptBlock
{
param([type]$Type)
[scriptblock]::Create('param($Value) [{0}]$Value' -f
[Microsoft.PowerShell.ToStringCodeMethods]::Type($Type))
}
然后,您可以将此脚本块分配给函数或直接调用它,例如:
(& (GenerateCastScriptBlock ([int])) "42").GetType()
关于.net - 使用存储在变量中的类型进行 PowerShell 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22794438/