C#是一个“字段”,但用作“类型”列表

时间:2013-11-11 05:05:40

标签: c# list

您好,这是我第一次发帖,所以如果我做错了,请纠正我。

我是初学者,我正在尝试使用winform和按钮作为控件制作一种文本冒险游戏。问题是当我尝试制作库存清单时。它给我一个语法错误说

  

“库存是'字段',但用作'类型'

这是有问题的代码:

public partial class MainGameWindow : Form
{ 
    //sets the room ID to the first room as default
    string roomID = "FirstRoom";
    //makes a list for the inventory
    List<string> Inventory = new List<string>();
    Inventory.Add("A piece of string...Useless!");
}

3 个答案:

答案 0 :(得分:11)

你不能在类的主体中有“动作”,你必须将它放在方法/函数或构造函数中,如

public partial class MainGameWindow : Form
{ 
    //sets the room ID to the first room as default
    string roomID = "FirstRoom";
    //makes a list for the inventory

    //collection initializer way (thanks to Max bellow!)
    List<string> Inventory = new List<string>()
    {
        "A piece of string...Useless!",
    };

    //constructor way
    public MainGameWindow()
    {
        Inventory.Add("A piece of string...Useless!");
    }

    //method way
    public void MethodAddUselessString()
    {
        Inventory.Add("A piece of string...Useless!");
    }

    //function way
    public bool FunctionAddUselessString()
    {
        Inventory.Add("A piece of string...Useless!");

        return true;
    }    
}

答案 1 :(得分:4)

您可以为Inventory使用集合初始值设定项语法:

public partial class MainGameWindow : Form
{
    List<string> Inventory = new List<string>()
    {
        "A piece of string...Useless!",
    };
}

答案 2 :(得分:1)

您正在课堂上致电Inventory.Add。你需要将它放在方法中。