Trouble with a simple Strategy Pattern example
The error is:
FirstPattern.Character.Character' does not contain a constructor that takes 0 arguments
Here is the code:
public interface WeaponBehavior
{
void UseWeapon();
}
class SwordBehavior : WeaponBehavior
{
public void UseWeapon()
{
Console.WriteLine("A sword as plain as your wife.");
}
}
Then, I have a character class:
public abstract class Character
{
WeaponBehavior weapon;
开发者_如何学JAVApublic Character(WeaponBehavior wb)
{
weapon = wb;
}
public void SetWeapon(WeaponBehavior wb)
{
weapon = wb;
}
public abstract void Fight();
}
public class Queen : Character
{
public Queen(WeaponBehavior wb)
{
SetWeapon(wb);
}
public override void Fight()
{
}
}
I'm not sure what I should be doing with the character class and subclasses. Can you guys nudge me in the right direction?
Since Queen
is derived from Character
and Character
only has a constructor with a WeaponBehavior
parameter, you need to explicitly call the base constructor in your Queen
constructor - that means the call to SetWeapon
you had in there is unnecessary as well:
public Queen(WeaponBehavior wb) : base(wb)
{
}
Alternatively you could offer a default constructor in Character
and leave your original code unchanged:
public abstract class Character
{
WeaponBehavior weapon;
public Character() { }
...
精彩评论