为什么我不能设置数组值?为什么不把它扔掉呢?

时间:2016-05-23 13:01:46

标签: c# arrays class casting non-static

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; }

    }

2 个答案:

答案 0 :(得分:3)

playersPlayer个对象的数组:

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构造函数。

编辑:将显式更改为隐式。隐式运算符将导致代码编译。