嗨,我正在尝试创建一个数组来存储一个垄断板上可用的所有位置,但是在创建该数组时,出现错误“无法隐式转换类型'(string,string,string,string,string,string )'串”。当然,代码已经将字符串转换为字符串应该不会有问题。为了进行编码,我将C#与Microsoft Visual Basic结合使用。
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", "", "");
}
答案 0 :(得分:2)
此语法:
("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.
}