所以我和一位同事就一段代码进行了友好的争论:
@H_502_11@解决方法
public sealed class NewObject { private string _stuff = string.Empty; public string Stuff { get { return GetAllStuff(); } } private string GetAllStuff() { //Heavy string manipulation of _stuff } public NewObject(string stuffToStartWith) { _stuff = stuffToStartWith; } public static NewObject operator +(NewObject obj1,NewObject obj2) { if (obj1 == null) throw new ArgumentNullException(); if (obj2 == null) throw new ArgumentNullException(); NewObject result = new NewObject(string.Empty); result._stuff = String.Concat(obj1._stuff,obj2._stuff); return result; } }
争论在于运算符覆盖.我的同事认为,除了构造函数之外,设置私有字段的值不是最好的编程习惯.我的同事提出的解决方案是将Stuff属性的名称重构为AllStuff,并添加一个属性Stuff,它具有get AND set访问器并在运算符覆盖中使用新的Stuff属性.看起来像这样:
public static NewObject operator +(NewObject obj1,NewObject obj2) { if (obj1 == null) throw new ArgumentNullException(); if (obj2 == null) throw new ArgumentNullException(); NewObject result = new NewObject(string.Empty); result.Stuff = String.Concat(obj1.Stuff,obj2.Stuff); return result; }
我不同意.我觉得第一种方式更好,因为它使属性在类外保持只读.我的问题是,哪种方式是面向对象设计的最佳实践?