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

C# record属性校验优化:如何移除实现中无意义的_dummy变量?

解决方案

你可以通过两种常用方式移除无意义的_dummy变量,两种实现都能完整保留原有校验功能:

方案1:显式实现record主构造函数(最推荐,无冗余成员)

直接把校验逻辑写入显式声明的主构造函数,完全不需要额外定义无用字段:

record Person(string FirstName, string LastName, int Age, Guid Id)
{
    // 显式声明主构造函数,调用编译器生成的默认构造逻辑,同时嵌入校验规则
    public Person(string firstName, string lastName, int age, Guid id) : this(firstName, lastName, age, id)
    {
        Check.StringArg(firstName);
        Check.StringArg(lastName);
        Check.IntArg(age);
    }

    internal static class Check
    {
        // 可调整为无返回值,无需为适配字段初始化表达式返回多余布尔值
        internal static void StringArg(string s)
        {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentException("参数不能为null或空字符串");
        }

        internal static void IntArg(int a)
        {
            if (a < 0)
                throw new ArgumentException("参数不能为负数");
        }
    }
}

该方案逻辑清晰透明,校验逻辑和构造流程直接绑定,没有任何无意义的类成员,是最符合C#编码规范的实现方式。

方案2:用丢弃变量(_)代替命名字段

如果不想改动原有校验逻辑的写法,也不想显式声明构造函数,可以直接把无用字段名改为C#编码约定中的丢弃变量名_,避免出现语义不明的命名:

record Person(string FirstName, string LastName, int Age, Guid Id)
{
    // 用下划线作为丢弃变量名,符合C#通用编码约定
    private readonly bool _ = 
        Check.StringArg(FirstName) && Check.StringArg(LastName) && Check.IntArg(Age);

    internal static class Check
    {
        static internal bool StringArg(string s)
        {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentException("参数不能为null或空字符串");
            return true;
        }

        static internal bool IntArg(int a)
        {
            if (a < 0)
                throw new ArgumentException("参数不能为负数");
            return true;
        }
    }
}

该方案改动量极小,仅需修改字段名即可,原有校验逻辑无需做任何调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:06:08