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

继承Command的类无法添加Option的问题求助

问题原因及解决建议

核心原因

你引用的System.CommandLine.DragonFruit包会通过源代码生成机制自动创建RootCommand实例,它会根据Main方法的签名生成默认命令结构,完全覆盖了你自定义的RootCommand类的构造逻辑。这就是为什么你的自定义构造函数断点没触发,且添加的--execute选项不被识别——实际运行时用的是DragonFruit自动生成的RootCommand,而非你写的那个。

解决方案

方案1:移除DragonFruit包,完全手动控制命令结构

如果你需要自定义RootCommand的完整逻辑,直接移除System.CommandLine.DragonFruit的包引用:

<!-- 从项目文件中删除这一行 -->
<PackageReference Include="System.CommandLine.DragonFruit" Version="0.4.0-alpha.22272.1" />

然后修改Main方法,手动实例化你的自定义RootCommand:

public sealed class Cli
{
    public static async Task Main(string[] args)
    {
        var rootCommand = new RootCommand(); // 实例化你自定义的RootCommand
        var parser = new CommandLineBuilder(rootCommand).UseDefaults().Build();
        await parser.InvokeAsync(args);
    }
}

方案2:保留DragonFruit,用特性标记定义选项(适合简单场景)

如果想继续用DragonFruit的便捷性,不需要自定义RootCommand类,直接在Main方法参数上用[Option]特性标注:

public sealed class Cli
{
    public static async Task Main(
        [Option("--execute", "-e", Description = "If this option is set to true the request will be processed without starting the REPL.")] 
        bool execute = true)
    {
        if (!execute)
        {
            Repl.Instance.Listen();
        }
        else
        {
            Debug.Print($"###  success  ###");
            Console.ReadLine();
        }
    }
}

DragonFruit会自动根据参数生成对应的选项,无需手动创建Option实例。

方案3:禁用DragonFruit的自动生成,保留自定义RootCommand

如果必须同时保留DragonFruit包和自定义RootCommand,可以在项目文件中添加配置关闭自动生成:

<PropertyGroup>
  <SystemCommandLineDragonFruitDisableSourceGeneration>true</SystemCommandLineDragonFruitDisableSourceGeneration>
</PropertyGroup>

之后Main方法就可以正常使用你自定义的RootCommand类,构造函数的逻辑会被执行。

调试补充说明

断点提示"No symbols loaded for this document",是因为DragonFruit生成的代码没有符号文件,而你的自定义RootCommand类实际上没被加载运行,所以断点不会触发。解决上述问题后,自定义类的符号会正常加载,断点就能正常工作。

内容的提问来源于stack exchange,提问作者crt.soluble

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:13:22