【发布时间】:2023-03-14 19:44:01
【问题描述】:
class BaseClass
{
public int Field = 1;
}
class DerivedA : BaseClass
{
public int SetField6()
{
return this.Field = 6;
}
}
class DerivedB : BaseClass
{
public int SetField16()
{
return this.Field = 16;
}
}
BaseClass x = new BaseClass();
int xField = x.Field;
DerivedA y = new DerivedA();
int yField = y.SetField6();
DerivedB z = new DerivedB();
int zField = z.SetField16();
int baseField = new BaseClass().Field;
在这种情况下,当DerivedA 和DerivedB 类中Field 的值发生更改时,BaseClass 类中Field 的值不会更改。所以baseField的值还是1。
- 是否可以在派生类
BaseClass类中更改Field的值? - 是否有适用于这种场景的设计模式?它叫什么?
【问题讨论】:
-
你为什么要给我们使用神秘名称的示例代码?你知道听你说的有多么困难吗?
-
好的...... 20 分钟后,我已经重构并重新表述了所有内容......希望现在其他人应该更容易阅读。
-
服务真好,@Jeff。人们应该更频繁地在这里用餐
标签: c# oop inheritance