C#:如何在子类重写基类可覆盖字段值且不强制其他子类设置
解决方案
针对你的需求,有两种常见实现方式,既可以在Tiger类中硬编码_name的值,又不会强制其他子类必须设置该字段:
方法一:直接在子类构造函数中赋值(基于现有代码)
因为基类的_name是public字段,子类可以直接在构造函数中修改它的值:
public class Animal { public string _name = "Animal"; public string GetGreeting() { if (this._name == "Animal") { return "Hello friend!"; } else { return $"Hello, '{this._name}'"; } } } public class Tiger : Animal { public Tiger() { // 硬编码Tiger的_name值 _name = "Tiger"; } }
其他子类如果不需要修改_name,直接继承Animal即可,无需额外代码。
方法二:封装字段的规范写法(推荐)
把基类的_name改为protected(仅允许子类访问),避免外部随意修改,同时保持子类灵活赋值的能力:
public class Animal { // 改为protected,仅子类可访问,提升封装性 protected string _name = "Animal"; public string GetGreeting() { if (this._name == "Animal") { return "Hello friend!"; } else { return $"Hello, '{this._name}'"; } } } public class Tiger : Animal { public Tiger() { _name = "Tiger"; } } // 其他子类无需设置_name,直接使用默认值 public class Rabbit : Animal { // 空实现即可,_name默认是"Animal" }
补充说明
- 不推荐在子类中用
new关键字重新声明_name(比如public new string _name = "Tiger";),这会隐藏基类字段,容易引发逻辑混乱。 - 如果后续需要更灵活的赋值方式,也可以给基类添加带参数的构造函数,但这会强制子类必须显式调用构造函数,不符合你“不强制其他子类设置”的需求,所以上述两种方法更适合。
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

