简单策略模式示例的问题
错误是:
FirstPattern.Character.Character' 确实 不包含采用 0 的构造函数 论据
这里是代码:
public interface WeaponBehavior
{
void UseWeapon();
}
class SwordBehavior : WeaponBehavior
{
public void UseWeapon()
{
Console.WriteLine("A sword as plain as your wife.");
}
}
然后,我有一个字符类:
public abstract class Character
{
WeaponBehavior weapon;
public 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()
{
}
}
我不确定应该对字符类和子类做什么。你们能把我推向正确的方向吗?
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;
public 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
Queen
派生自Character
并且Character
只有一个带有WeaponBehavior
参数的构造函数,因此您需要显式调用Queen
构造函数中的基本构造函数 - 这意味着对其中的SetWeapon
的调用也是不必要的:或者,您可以在
Character< 中提供默认构造函数/code> 并保持原始代码不变:
Since
Queen
is derived fromCharacter
andCharacter
only has a constructor with aWeaponBehavior
parameter, you need to explicitly call the base constructor in yourQueen
constructor - that means the call toSetWeapon
you had in there is unnecessary as well:Alternatively you could offer a default constructor in
Character
and leave your original code unchanged: