You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中加载Spectre.Console泛型类SelectionPrompt失败的问题

在PowerShell中使用Spectre.Console的泛型SelectionPrompt类

PowerShell无法直接引用开放泛型类型,必须指定具体的类型参数才能正确访问SelectionPrompt。以下是正确的实现方式:

完整示例代码

# 加载Spectre.Console程序集
Add-Type -AssemblyName ".\path\to\Spectre.Console.dll"

# 创建针对字符串类型的SelectionPrompt实例
$prompt = [Spectre.Console.SelectionPrompt[string]]::new()
$prompt.Title = "请选择一个操作"
# 添加可选选项
$prompt.AddChoices("启动服务", "停止服务", "退出")

# 显示交互式提示并获取结果
$selected = [Spectre.Console.AnsiConsole]::Prompt($prompt)

Write-Host "你选择了: $selected"

错误原因说明

你之前的写法$select = [Spectre.Console.SelectionPrompt]尝试引用开放泛型类型,而PowerShell要求必须指定泛型参数(比如string)才能识别具体的封闭泛型类,语法格式为[Namespace.ClassName[Type]](方括号用于标记类型参数)。

如果需要动态指定泛型类型,也可以通过开放泛型类型构造封闭类型:

# 获取开放泛型类型(`1表示该类有1个泛型参数)
$openGenericType = [Spectre.Console.SelectionPrompt``1]
# 构造针对int类型的封闭泛型类型
$closedType = $openGenericType.MakeGenericType([int])
# 创建实例
$prompt = [Activator]::CreateInstance($closedType)
$prompt.Title = "选择一个数字"
$prompt.AddChoices(1, 2, 3, 4, 5)

$selectedNum = [Spectre.Console.AnsiConsole]::Prompt($prompt)
Write-Host "你选择的数字是: $selectedNum"

内容的提问来源于stack exchange,提问作者loldfield

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:15:32