How to fill an inherited array in C#?
I'm writing a game, which uses two different dice. They are both 12-sided, but contain different values (specifically animals) on their faces. I wrot开发者_运维知识库e a base Dice class, which looks like this:
public abstract class Dice
{
private DieFace[] faces;
public DieFace RollDie()
{
//return random value from faces
}
public abstract void FillDieFaces();
}
"DieFace" is an enum with different names of animals which I'll use for the dice.
Now I want to write two classes, which inherit from Dice - RedDie and YellowDie, which are identical except for the values they can produce. The problem I'm having is that I'm not sure how to access the faces array in the inheriting classes. I can't implement FillDieFaces() in the base class, because it's meaningless without specific values. Can you please recommend a good way of doing what I'm trying to do?
Thanks for any help you can give.
Best regards, Bertold
You can make faces
protected
instead of private
, so it will be accessible from the child classes.
This would look like this:
public abstract class Dice
{
protected DieFace[] faces;
public DieFace RollDie()
{
//return random value from faces
}
public abstract void FillDieFaces();
}
public class RedDie : Dice
{
public override void FillDieFaces()
{
// assign to faces
}
}
public class YellowDie : Dice
{
public override void FillDieFaces()
{
// assign to faces
}
}
As well as Mark's answer (make the array protected), you could also override a method that returns the values instead and call that from FillDieFaces
public abstract class Dice
{
private DieFace[] faces;
protected abstract DieFace[] GetDieFaces();
public void FillDieFaces()
{
faces = GetDieFaces();
}
}
public class AnimalDice : Dice
{
protected override DieFace[] GetDieFaces()
{
return new DieFace[] { DieFace.Panda, DieFace.Unicorn };
}
}
or even move the FillDieFaces code into base class constructor instead.
精彩评论