C# 列表帮助 - 'items' 在当前上下文中不存在

C# List help - 'items' does not exist in the current context

我正在 Viusal Studio 中制作主机游戏,并制作了一个商店 class 和一个物品 class,如下所示:

Item.cs -

public class Item
{
    string name;
    string type;
    string description;

    int damage = 0;

    public Item(string name, string type, string description, int damage)
    {
        this.Name = name;
        this.Type = type;
        this.Description = description;
        this.Damage = damage;
    }

    public string Name { get => name; set => name = value; }
    public string Type { get => type; set => type = value; }
    public string Description { get => description; set => description = value; }
    public int Damage { get => damage; set => damage = value; }    
}

Shop.cs -

    public class Shop
{
    List<Item> items = new List<Item>();
    Item sword = new Item("Sword", "Meele", "Plain old sword", 10);
    public string shopName;
}

我在 Shop.cs class 中制作了一个项目列表。但是我不能在Shop.csclass里面调用'items'列表?这是为什么?如果我写列表的名称,例如 items.Add,它会抛出一个错误:'items' 在当前上下文中不存在。

有人可以解释为什么吗?

您必须在 c# 的方法内部执行指令,因此第一个代码片段不会 运行 它会引发错误。

  public class Shop
  {
    List<Item> items = new List<Item>();
    Item sword = new Item("Sword", "Meele", "Plain old sword", 10);


    //This needs to be in a method or constructor
    items.add(sword);

    public string shopName;
  }

您必须这样做,因为“在 C# 中,每条执行的指令都是在方法的上下文中执行的”。

阅读有关 C# 方法的更多信息:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods

尝试类似下面的代码片段来修复您的错误。

  public class Shop
  {
    public Shop()
    {
      items.Add(sword);
    }

    List<Item> items = new List<Item>();
    Item sword = new Item("Sword", "Meele", "Plain old sword", 10);
    public string shopName;
  }