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

如何在C#建造者模式中强制首个方法的调用顺序?

如何通过IntelliSense强制建造者模式的首个方法调用顺序?

你遇到的问题核心在于:直接实例化Builder类时,它实现的所有接口方法都会暴露给IntelliSense,没法限制必须先调用First()。要解决这个问题,关键是不让外部直接拿到Builder类的实例,而是只返回对应阶段的接口类型,具体可以这么改:

修改后的实现代码

public interface IFirst
{
    ISecond First();
}

public interface ISecond
{
    IThird Second();
}

public interface IThird
{
    int Third();
}

public class Builder : IFirst, ISecond, IThird
{
    // 把构造函数设为私有,外部不能直接new
    private Builder()
    {
    }

    private int _counter = 0;

    public ISecond First()
    {
        _counter++;
        return this;
    }

    public IThird Second()
    {
        _counter++;
        return this;
    }

    public int Third()
    {
        return _counter;
    }

    // 提供静态工厂方法,返回IFirst类型的实例
    public static IFirst Create()
    {
        return new Builder();
    }
}

public class BuilderConsumer
{
    public void Build()
    {
        // 现在只能通过Create()拿到IFirst,初始只能调用First()
        var count = Builder.Create().First().Second().Third();

        // 以下错误调用现在会直接编译报错,IntelliSense也不会显示对应的方法
        // var count2 = Builder.Create().Second().Third(); // 编译错误:IFirst没有Second方法
        // var count3 = Builder.Create().Third(); // 编译错误:IFirst没有Third方法
        // var builder = new Builder(); // 编译错误:Builder构造函数私有
    }
}

改动说明

  • 私有构造函数:阻止外部直接实例化Builder,强制必须通过工厂方法获取实例。
  • 静态工厂方法返回IFirst:外部拿到的初始类型是IFirst,IntelliSense只会显示First()方法,从根源上避免了跳过首个方法的可能。
  • 接口链式返回:每个方法返回下一个阶段的接口,确保调用顺序只能按First() → Second() → Third()的流程走,编译期就能拦截错误调用,完全不需要依赖运行时抛异常。

这样实现后,IntelliSense会严格按照阶段显示可用方法,用户根本看不到不允许调用的方法,自然不会出现顺序错误的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:20:26