C#中统计数组元素数量遇Count报错,求正确实现方法
解决C#数组调用Count报错的问题
嘿,这个问题我太熟悉啦!你碰到的错误根源很简单:C#里的数组(比如你的string[])没有Count()方法——Count是给List<T>、HashSet<T>这类实现了IEnumerable<T>的集合用的扩展方法,而数组的元素数量得用它的内置属性Length来获取。
先看你的原始代码里的错误点:
public static string[] traitNames = { "Happiness", "Respect", "Authority" }; public static string[] suppliesNames = { "Food", "Iron", "Gold" }; private List<string[]> arraysNames = new List<string[]> { traitNames, suppliesNames }; string[] currentArrayNames = arraysNames[i1]; int namesCount = currentArrayNames.Count;//ERROR HERE
错误提示Cannot convert method group "Count" to non-delegate type 'int'的意思是:编译器把Count当成了一个方法组(因为数组没有名为Count的属性),但你试图直接把它赋值给int变量,这就产生了类型不匹配的问题。
解决方案:用Length代替Count
只需要把错误行替换成下面的代码就行:
int namesCount = currentArrayNames.Length;
修正后的完整代码:
public static string[] traitNames = { "Happiness", "Respect", "Authority" }; public static string[] suppliesNames = { "Food", "Iron", "Gold" }; private List<string[]> arraysNames = new List<string[]> { traitNames, suppliesNames }; string[] currentArrayNames = arraysNames[i1]; int namesCount = currentArrayNames.Length; // 正确获取数组元素数量
额外小知识
Length是数组的固有属性,返回数组创建时就固定的元素总数,效率极高;Count()是System.Linq.Enumerable提供的扩展方法,适用于所有IEnumerable<T>类型的集合(包括数组),但调用它会走扩展方法的逻辑,效率不如直接用Length;- 如果你之后把数组换成
List<string>这类集合,用Count(属性,不是方法)就完全没问题啦。
内容的提问来源于stack exchange,提问作者Gabe Tucker
相关产品推荐
相关产品推荐

