【问题标题】:C# - Not being able to use list.Count() in this scenarioC# - 在这种情况下无法使用 list.Count()
【发布时间】:2015-05-13 12:10:49
【问题描述】:

我在编译过程中遇到了这个错误:

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

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

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!");
    }
}

【问题讨论】:

  • 你能引用确切的错误信息吗?
  • 错误是什么,是在编译还是运行时出现的?
  • 这可能有点离题,但你能解释一下你为什么不使用public List&lt;string&gt; inventory { get; set; }吗?
  • @Voidpaw,你觉得改变会给代码带来什么好处?
  • 从提供的代码来看,这在技术上是不可能的。所以,或者消息不准确,或者描述问题的代码不完整。

标签: c# list count compiler-errors


【解决方案1】:

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

【讨论】:

  • 没有解决问题。在没有命名空间的情况下会显示不同的错误。
  • OP 说“System.Collections.Generic.List.Count 由于其保护级别而无法访问”他的代码怎么可能?
  • @Francisco 使用 Count 属性而不是实际工作的方法。谢谢!
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    count 是属性而不是方法。

    在你的情况下应该是

    if (inventory.Count &lt; 3)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-16
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多