如何优化C# Note类构造器冗余代码?能否通过属性实现且避免私有变量?
优化构造器重复校验逻辑与避免私有变量的方案
1. 消除构造器重复逻辑:提取通用校验方法
把重复的字符串长度校验、默认值设置逻辑抽成私有静态方法,在构造器中直接调用,彻底消除重复代码:
public class Note { // 使用自动只读属性,无需手动声明私有字段(编译器自动生成) public string Title { get; } public string Content { get; } public string Tags { get; } public Note(string title, string content, string tags) { Title = ValidateInput(title, 50, "Untitled"); Content = ValidateInput(content, 1000, "Empty content"); Tags = ValidateInput(tags, 200, "No tags"); } // 通用校验方法,统一处理所有字符串属性的逻辑 private static string ValidateInput(string input, int maxLength, string defaultValue) { if (!string.IsNullOrEmpty(input) && input.Length <= maxLength) return input; return defaultValue; } }
2. 用属性访问器封装逻辑(支持属性修改场景)
如果需要允许后续修改属性值,同时保留校验逻辑,可以把校验逻辑嵌入属性的set(或C# 9+的init)访问器中。若想完全避免手动编写私有变量,可结合自动属性的特性,或使用record类型实现不可变类:
支持修改的属性实现(含私有字段但逻辑集中)
public class Note { private string _title; public string Title { get => _title; set => _title = ValidateInput(value, 50, "Untitled"); } private string _content; public string Content { get => _content; set => _content = ValidateInput(value, 1000, "Empty content"); } private string _tags; public string Tags { get => _tags; set => _tags = ValidateInput(value, 200, "No tags"); } public Note(string title, string content, string tags) { Title = title; Content = content; Tags = tags; } private static string ValidateInput(string input, int maxLength, string defaultValue) { return !string.IsNullOrEmpty(input) && input.Length <= maxLength ? input : defaultValue; } }
完全避免私有变量:使用Record类型
如果是不可变的Note类,用record类型可以彻底省去手动编写私有字段,同时保留校验逻辑:
public record Note(string Title, string Content, string Tags) { public string Title { get; } = ValidateInput(Title, 50, "Untitled"); public string Content { get; } = ValidateInput(Content, 1000, "Empty content"); public string Tags { get; } = ValidateInput(Tags, 200, "No tags"); private static string ValidateInput(string input, int maxLength, string defaultValue) { return !string.IsNullOrEmpty(input) && input.Length <= maxLength ? input : defaultValue; } }
3. 避免私有变量的核心思路
- 优先使用自动属性:编译器会自动生成对应的私有字段,无需手动编写,减少冗余代码。
- 不可变类场景:用只读自动属性(
{ get; })或record类型,把校验逻辑集中到通用方法或属性初始化中。 - 可变属性场景:将校验逻辑封装到
set/init访问器中,即使需要私有字段,也能通过通用方法避免重复逻辑。
内容的提问来源于stack exchange,提问作者Дмитрий Витязь
相关产品推荐
相关产品推荐

