C# - 在这种情况下无法使用 list.Count()

C# - Not being able to use list.Count() in this scenario

我在编译期间遇到此错误:

System.Collections.Generic.List<string>.Count is inaccessible due to its protection level

关于尝试在我创建的代表项目清单的列表上使用方法 Count()。该列表本身是 public,所以我无法理解为什么会这样......(这里是新手)

public class Inventory
{
    private List <string> _inventory;
    public List<string> inventory {get; set;}

    public Inventory ()
    {
        _inventory = new List<string>();
        inventory = _inventory;
    }

    public void AddItem(string str)
    {
        if (inventory.Count() < 3)  //    error pops up here...
            inventory.Add(str); 
        else
            Console.WriteLine ("Your inventory is full!");
    }
}

使用 List 时,您应该使用 属性 Count,而不是 Count() 方法。 Count() 是一种扩展方法,您需要导入 System.Linq 才能使用它。

count 是 属性 而不是方法。

在你的情况下应该是

if (inventory.Count < 3)

我认为这可能发生的唯一方法是,如果您以某种方式重写了 List 上的 Count 方法或为 List 实现了您自己的 class。你做过这两件事吗?如果是这样,请不要,它应该修复它。