简单策略模式示例的问题

发布于 2024-10-15 19:02:43 字数 849 浏览 3 评论 0原文

错误是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莳間冲淡了誓言ζ 2024-10-22 19:02:43

由于 Queen 派生自 Character 并且 Character 只有一个带有 WeaponBehavior 参数的构造函数,因此您需要显式调用Queen 构造函数中的基本构造函数 - 这意味着对其中的 SetWeapon 的调用也是不必要的:

public Queen(WeaponBehavior wb) : base(wb)
{
}

或者,您可以在 Character< 中提供默认构造函数/code> 并保持原始代码不变:

public abstract class Character
{
   WeaponBehavior weapon;

   public Character() { }
   ...

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() { }
   ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文