我有抽象基类,包含一些字段和一些作用于这些字段的方法.例如:
public abstract class A { protected double _field; public double SquaredField { get { return _field * _field; } } ... some other abstract methods }
我想强制A的所有孩子在他们的构造函数中初始化_field
public class B : A { public B(double field) { _field = Math.Sqrt(field); } ... some other method implementations }
实现这一目标的正确模式是什么?
– 编辑
我最终做的是:
public abstract class A { protected readonly double _field; public A(double field) { _field = field; } public double SquaredField { get { return _field * _field; } } ... some other abstract methods } public class B : A { public B(double field) : base(field) { } public static B CreateNew(double val) { return new B(Math.Sqrt(field)); } ... some other method implementations }
解决方法
根本不要将字段公开给派生类.相反,创建一个受保护的抽象属性:
public abstract class A { protected double Field { get; } public double SquaredField { get { return Field * Field; } } }
或者,如果字段对于特定实例应始终保持不变,请将其作为构造函数参数并将其保持为私有:
public abstract class A { private readonly double _field; public double SquaredField { get { return _field * _field; } } protected A(double field) { _field = field; } }