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

C#能否为record定义私有构造函数以限制根记录类型的派生实现?

解决方案

你只需给根抽象record显式声明私有构造函数即可,实现逻辑和你最初用类实现Discriminated Union的思路完全一致:

public abstract record Result
{
    // 私有构造函数,仅内部嵌套类型可访问
    private Result() {}
    public sealed record Ok(object result) : Result;
    public sealed record Error(string message) : Result;
}

原理解释

所有派生类型实例化时都必须调用基类的构造函数,将根Result的构造函数设为private后,只有定义在Result内部的嵌套类型Ok、Error有权限访问该构造函数。外部任何类型尝试继承Result时,都会因为无法访问有效基类构造函数触发编译错误,彻底避免了外部新增派生实现的问题。

如果你的根record需要带参数的构造,也可以将带参构造的访问修饰符设为private,嵌套子record显式调用即可:

public abstract record Result
{
    private Result(int code) => Code = code;
    public int Code { get; }
    
    public sealed record Ok(object result, int code) : Result(code);
    public sealed record Error(string message, int code) : Result(code);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:45:01