0

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

我是一个初学者,我正在尝试制作一种仅使用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!");
}
4

3 回答 3

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;
    }    
}
于 2013-11-11T05:09:07.990 回答
4

您可以将集合初始化器语法用于Inventory

public partial class MainGameWindow : Form
{
    List<string> Inventory = new List<string>()
    {
        "A piece of string...Useless!",
    };
}
于 2013-11-11T05:11:11.513 回答
1

你正在Inventory.Add上课。你需要把它放在方法里面。

于 2013-11-11T05:09:51.593 回答