.net - 使用存储在变量中的类型进行 PowerShell 类型转换

标签 .net powershell

我想将 .NET 对象转换为另一种 .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/

    相关文章:

    powershell - 从日志文件中选择主机名

    c# - 如何阻止 JIT 调试器介入崩溃的 wcf 服务?

    c# - 重写 .NET WebBrowsers WndProc

    c# - 将自定义 EventArgs 作为事件参数传递

    powershell - 查找哪个哈希表键值

    powershell - 在Powershell上相当于Unix的命令

    powershell - Powershell喷溅插入额外的字符

    .net - 如何在 PowerShell 中删除点源脚本?

    c# - 如何在 Visual Studio for C# 项目中使用自定义框架而不是 .NET?

    .net - EF4 可以使用自定义约定从数据库生成模型