【问题标题】:Problem with my array while making monopoly game制作垄断游戏时我的阵列出现问题
【发布时间】:2020-03-07 00:53:34
【问题描述】:

我正在尝试创建一个数组来存储垄断板上所有可用的位置,但是在创建数组时出现错误

"不能隐式转换类型'(string,string,string,string,string)' 字符串”

.

 private void pictureBox1_Click_1(object sender, EventArgs e)
        {
            string[,,,,]BoardPos;
            BoardPos = new string[39, 0, 4, 0, 0];
            BoardPos[0, 0, 0, 0, 0] = ("Go", "+200", "CurrentPlayer", "", "");
            BoardPos[1, 0, 0, 0, 0] = ("Old Kent Road", "-60", "CurrentPlayer", "", "");
        }

【问题讨论】:

  • ("Go", "+200", "CurrentPlayer", "", "") 是四个字符串的值元组。 BoardPos[0, 0, 0, 0, 0] 是多维数组中的单个字符串。

标签: c# arrays string multidimensional-array


【解决方案1】:

这个语法:

("Go", "+200", "CurrentPlayer", "", "");

实际上是在创建一个字符串元组,而不是一个字符串数组。

解决方法是重写代码以利用 C# 的面向对象特性。我建议您通过创建一个包含相关字段的类来简化代码:

public interface IMonopolySquare
{
     public string Name { get; }
     public void PlayerLandsOnEvent(Player player);
     public void PlayerPassesSquareEvent(Player player);
     public void SetOwner(Player player);
}

public class GoSquare : IMonopolySquare
{
     public string Name { get => "Go" }

     public void PlayerLandsOnEvent(Player player)
     {
          // Do nothing - player has to pass to receive £200.
     }

     public void PlayerPassesSquareEvent(Player player)
     {
         player.AddMoney(200);
     }

    public void SetOwner(Player player)
    {
        throw new Exception ("You can't buy go!!");
    }
}

public class PropertySquare : IMonopolySquare
{
    private Player _owner = null;
    private int _rentWithoutHouse;
    private Color _color;

    public PropertySquare(
        string name,
        int rentWithoutHouse,
        Color color)
    {
        Name = name;
        _rentWithoutHouse = rentWithoutHouse;
        _color = color;
    }

    public string Name {get;}
     public void PlayerLandsOnEvent(Player player)
     {
         if (_owner != null && _owner != player)
         {
             player.SubtractMoney(_rentWithoutHouse); 
         }
     }

     public void PlayerPassesSquareEvent(Player player)
     {
         // Do nothing.
     }

    public void SetOwner(Player player)
    {
        if (owner != null)
        {
            throw new Exception("Can't buy something that's already been bought!");
        }
        else
        {
            _owner = player;
        }
    }
}

// the Player class is left as an exercise for the reader...

然后你的“板子”就变得简单多了:

var board = new IMonopolySquare[] {
    new GoSquare(),
    new PropertySquare("Old Kent Road", "2", Color.Brown),
    // etc.
}

【讨论】:

  • 不应该GoSquare实现IMonopolySquare吗?
  • 太棒了!非常感谢
猜你喜欢
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
相关资源
最近更新 更多