Private Player[] players = new Player[2];
private int currentPlayerIndex = 0;
public Game(Form1 form)
{
for (int i = 0; i < players.Length; i++) {
players[i] = (string)"Player"; }
我一直收到一个错误,说它无法将字符串转换为播放器类型...
以下是播放器类,它还为Name ...
设置属性class Player
{
private string name = "";
public Player(string name)
{
name = "Player";
}
public string Name {
get { return name; }
set { name = value; }
}
答案 0 :(得分:3)
players
是Player
个对象的数组:
private Player[] players = new Player[2];
您正在尝试在数组中放入一个字符串。
players[i] = (string)"Player";
这不起作用,您只能在数组
中放置Player
的实例
players[i] = new Player("Player1");
答案 1 :(得分:-2)
因为您的代码没有从字符串向Player提供implicit cast。你需要这样的东西:
public static implicit operator Player(string str)
{
return new Player(str);
}
当然,您需要一个带有字符串参数的Player构造函数。
编辑:将显式更改为隐式。隐式运算符将导致代码编译。