C# 运算符不能应用于“方法组”和“整数”类型的操作数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19526702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:11:50  来源:igfitidea点击:

Operator cannot be applied to operands of type 'Method Group' and 'int'

c#arraysfor-loop

提问by Nathan

I'm trying to get the number of elements in this string array, but it won't let me take 1 away from Count.

我正在尝试获取此字符串数组中的元素数,但它不会让我从Count.

string [] Quantitys = Program.RecieptList[i].ItemQuantitys.Split(new char[] {'*'});
for (int ii = 0; i <= Quantitys.Count - 1; ii++)
{

}

I get an error message stating

我收到一条错误消息,说明

Operator '-' cannot be applied to operands of type 'Method Group' and 'Int'.

运算符“-”不能应用于“方法组”和“Int”类型的操作数。

Whats the proper way to do this?

这样做的正确方法是什么?

回答by valverij

It should be Lengthnot Countfor arrays:

它应该是Length没有Count数组:

string [] Quantitys = Program.RecieptList[i].ItemQuantitys.Split(new char[] {'*'});
for (int ii = 0; i <= Quantitys.Length - 1; ii++)
{

}

More information on the MSDN: Array.Length

MSDN 上的更多信息:Array.Length

Also, unless it was intentional, your iishould just be iin your forloop:

此外,除非是故意的,否则您ii应该ifor循环中:

for (int i = 0; i <= Quantitys.Length - 1; i++)

Although, as was pointed out in the comments below, you could also use the Quantitys.Count(), since arrays inherit from IEnumerable<T>. Personally, though, for one-dimensional arrays, I prefer to use the standard Array.Lengthproperty.

虽然,正如在下面的评论中指出的,您也可以使用 Quantitys.Count(),因为数组继承自IEnumerable<T>. 不过,就我个人而言,对于一维数组,我更喜欢使用标准Array.Length属性。

回答by Tim S.

Arrays have a Lengthproperty, not a Countproperty, though they do the same thing. The error you're seeing is because there's an extension method Count()that it's finding instead, but can't quite use because you didn't invoke it with (). You could use your array as an IList<T>instead so that you can keep the familiar Countproperty name.

数组有一个Length属性,而不是一个Count属性,尽管它们做同样的事情。您看到的错误是因为Count()它找到了一个扩展方法,但不能完全使用,因为您没有使用(). 您可以使用您的数组作为IList<T>替代,以便您可以保留熟悉的Count属性名称。

Also, iand iiwill be confusing to most people (including yourself, from the looks of it: you included both in your forline). The standard in programming, carried over from mathematics, is i, j, k, ... for index variable names. This will work:

此外,i并且ii会让大多数人感到困惑(包括您自己,从外观上看:您将两者都包含在您的for行中)。从数学继承而来的编程标准是i, j, k, ... 用于索引变量名称。这将起作用:

IList<string> Quantitys = Program.RecieptList[i].ItemQuantitys.Split(new char[] {'*'});
for (int j = 0; j <= Quantitys.Count - 1; j++)
{

}

回答by KDWolf

Simply add brackets (). Count() works for me now as well

只需添加括号 ()。Count() 现在也适用于我