使用存储在变量中的类型进行PowerShell类型转换 [英] PowerShell type cast using type stored in variable

查看:197
本文介绍了使用存储在变量中的类型进行PowerShell类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将.NET对象转换为其他.NET类型,但是:




  • 目标.NET类型(类)存储在变量中

  • 我不想使用 -as PowerShell运算符

  • 我使用的是复杂的非原始类型



您将如何实现?



例如,这是 PowerShell方法,但我不想使用 -as

  $ TargetType = [System.String]; #我要转换为
1的类型-as $ TargetType; #将对象强制转换为$ TargetType

不幸的是,这不起作用:

  $ TargetType = [System.String]; 
[$ TargetType] 1;

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

我在想类似的东西:

  $ TargetType = [系统。串]; 
$ TargetType.Cast(1); #.NET框架中是否存在类似的内容?

可以使用.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( )


I'd like to cast a .NET object to another .NET type, but:

  • The target .NET type (class) is stored in a variable
  • I don't want to use the -as PowerShell operator
  • I am using complex, non-primitive types

How would you achieve this?

For example, this is the "PowerShell" way to do it, but I don't want to use -as:

$TargetType = [System.String]; # The type I want to cast to
1 -as $TargetType;             # Cast object as $TargetType

Unfortunately, this does not work:

$TargetType = [System.String];
[$TargetType]1;

.. because PowerShell does not allow the use of variables inside the square brackets, in this scenario.

I am imagining something like:

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

Can it be done with .NET method syntax? Is there a static method that does this?

解决方案

You can roughly emulate a cast using the following method:

[System.Management.Automation.LanguagePrimitives]::ConvertTo($Value, $TargetType)

A true cast may behave differently than the above method for dynamic objects that provide their own conversions. Otherwise, the only other difference I can think of is performance - a true cast may perform better because of optimizations not available in the ConvertTo static method.

To precisely emulate a cast, you'll need to generate a script block with something like:

function GenerateCastScriptBlock
{
    param([type]$Type)

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

You can then assign this script block to a function or invoke it directly, e.g.:

(& (GenerateCastScriptBlock ([int])) "42").GetType()

这篇关于使用存储在变量中的类型进行PowerShell类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆