强制子类初始化字段

d--*_*--b 7 c# oop

我有抽象基类,包含一些字段和一些作用于这些字段的方法.例如:

public abstract class A
{
    protected double _field;

    public double SquaredField { get { return _field * _field; } }

    ... some other abstract methods
}
Run Code Online (Sandbox Code Playgroud)

我想强制A的所有孩子在他们的构造函数中初始化_field

public class B : A
{
    public B(double field)
    {
         _field = Math.Sqrt(field);
    }

    ... some other method implementations
}
Run Code Online (Sandbox Code Playgroud)

实现这一目标的正确模式是什么?

- 编辑

我最终做的是:

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
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 10

根本不要将字段公开给派生类.相反,创建一个受保护的抽象属性:

public abstract class A
{
    protected double Field { get; }

    public double SquaredField { get { return Field * Field; } }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果字段对于特定实例应始终保持不变,请将其设为构造函数参数并将其保持为私有:

public abstract class A
{
    private readonly double _field;

    public double SquaredField { get { return _field * _field; } }

    protected A(double field)
    {
        _field = field;
    }
}
Run Code Online (Sandbox Code Playgroud)