gpt4 book ai didi

c# - 一个简单的策略模式示例的问题

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:44 26 4
gpt4 key购买 nike

错误是:

FirstPattern.Character.Character' does not contain a constructor that takes 0 arguments

代码如下:

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()
{

}
}

我不确定我应该如何处理字符类和子类。你们能把我推向正确的方向吗?

最佳答案

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

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

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

public abstract class Character
{
WeaponBehavior weapon;

public Character() { }
...

关于c# - 一个简单的策略模式示例的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4882318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com