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

能否通过接口强制实现方法的部分逻辑?C#插件开发场景

解决方案:抽象基类 + 模板方法模式

要统一退出逻辑并避免重复代码,最直接的方式是用抽象基类封装公共逻辑,结合模板方法模式让子类只实现差异化的业务代码。具体步骤如下:

1. 定义抽象基类,封装公共逻辑

创建一个继承ICommand的抽象基类,把Running属性、Execute方法的循环结构和统一退出逻辑放在这里,只留业务逻辑部分给子类实现:

public abstract class BaseCommand : ICommand
{
    // 子类必须实现命令名称和描述
    public abstract string Name { get; }
    public abstract string Description { get; }

    // 私有字段控制循环,避免子类随意修改
    private bool _running = true;
    public bool Running { get => _running; private set => _running = value; }

    // 固定的Execute流程,强制所有子类遵循
    public int Execute()
    {
        while (_running)
        {
            // 调用子类的业务逻辑
            ExecuteBusinessLogic();
            
            // 统一的退出判断逻辑,所有命令共用
            CheckAndHandleExit();
        }
        return 0;
    }

    // 子类必须实现的业务逻辑方法
    protected abstract void ExecuteBusinessLogic();

    // 统一的退出逻辑,私有方法确保子类无法修改
    private void CheckAndHandleExit()
    {
        Console.Write("\n输入'exit'退出当前命令:");
        var input = Console.ReadLine()?.Trim().ToLower();
        if (input == "exit")
        {
            _running = false;
            Console.WriteLine("已退出命令");
        }
    }
}

2. 子类仅实现业务逻辑

子类继承抽象基类,只需实现命令名称、描述和自己的业务逻辑,无需再写循环和退出代码:

public class HelloCommand : BaseCommand
{
    public override string Name => "hello";
    public override string Description => "Displays hello message.";

    protected override void ExecuteBusinessLogic()
    {
        // 这里写当前命令的专属业务代码
        Console.WriteLine("Hello World!");
    }
}

// 另一个示例命令
public class GreetCommand : BaseCommand
{
    public override string Name => "greet";
    public override string Description => "Greets the user.";

    protected override void ExecuteBusinessLogic()
    {
        Console.Write("请输入你的名字:");
        var name = Console.ReadLine();
        Console.WriteLine($"你好,{name}!");
    }
}

3. 调用方式

使用时直接实例化子类,调用Execute方法即可,所有命令都会自动遵循统一的循环和退出逻辑:

var helloCmd = new HelloCommand();
helloCmd.Execute();

var greetCmd = new GreetCommand();
greetCmd.Execute();

为什么用抽象基类而不是接口?

接口只能定义契约(方法/属性签名),无法包含具体实现;而抽象基类既可以强制子类遵循契约,又能封装公共逻辑,完美解决你需要统一退出逻辑、避免重复代码的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:11:59