class BaseClass
{
public int Field = 1;
}
class DerivedA : BaseClass
{
public int SetField6()
{
return this.Field = 6;
}
}
class DerivedB : B开发者_如何学运维aseClass
{
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;
In this scenario when the value of Field
is changed in the DerivedA
and DerivedB
classes, the value of Field
in the BaseClass
class is not changed. So the value of baseField
is still 1
.
- Is it possible to change the value of
Field
in the class,BaseClass
from a derived class? - Is there a design pattern for this scenario and what is it called?
When you instantiate each object, it creates its own memory in heap till it roots i.e Object class. And all the memebers in every class of the heirarchy is created in stack (if its valuetype).
Hence its different in each case.
First, what might be the fix: make the field you want changed by subclasses static
in the base class. I'm not sure if this will really give you the behavior you expect, because it's unclear just what that behavior is. If you do this, every instance will share the same value.
Second, this is all unclear because (I think) you're confusing classes with instances here.
To use a pretty common metaphor for this, it's the difference between the blueprint for a house and the house itself.
The question you just asked is: if I make a house from blueprint Z, and I break a window in that house, why aren't any windows broken in a new house made from the same blueprint?
The house in this metaphor is the instance (x
), the blueprint is the class(BaseClass
).
You can make Field in BaseClass static to get what you want (although I really can't understand what you are trying to achieve)
1. Is it possible to change the value of Field in the class, BaseClass from a derived class?
You have actually done that in your scenario, but it is hidden by that last line of code (because you are instantiating a new object which gets a fresh Field setup to be 1). So, instead of calling:
int baseField = new BaseClass().Field;
Use this:
int baseField = y.Field; // baseField is now = 6 because Field was changed earlier by y.SetField6()
This way, you can actually see that the value of the base member Field has been modified by an object constructed from a derived class (the actual modification was done by calling y.SetField6()).
2. Is there a design pattern for this scenario and what is it called?
Yes, it is called object inheritance.
精彩评论