PowerShell type cast using type stored in variable

前端 未结 1 1933
轮回少年
轮回少年 2021-01-14 02:42

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
相关标签:
1条回答
  • 2021-01-14 03:04

    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()
    
    0 讨论(0)
提交回复
热议问题