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

use*_*903 0 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!");
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*dou 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;
    }    
}
Run Code Online (Sandbox Code Playgroud)