gpt4 book ai didi

c# - 强制子类初始化字段

转载 作者:太空狗 更新时间:2023-10-29 19:58:35 35 4
gpt4 key购买 nike

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

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
}

最佳答案

根本不要向派生类公开字段。相反,创建一个 protected 抽象属性:

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

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

或者,如果该字段对于特定实例应始终为常量,则将其设为构造函数参数并保持私有(private):

public abstract class A
{
private readonly double _field;

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

protected A(double field)
{
_field = field;
}
}

关于c# - 强制子类初始化字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11970956/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com