[英]C# Impossible to convert method group to bool?
public void nbOccurences(int[] base1, int n, int m)
{
foreach (int i in base1)
{
if (n == 32)
{
m++;
}
}
}
static void Main(string[] args)
{
int chiffrebase = 32;
int occurence = 0;
int[] test123 = new int[] { 12, 32, 33, 64, 75, 46, 42, 32 };
Program n1 = new Program();
n1.nbOccurences(test123, chiffrebase, occurence);
Console.WriteLine(nbOccurences);
}
我不断收到“无法从方法组转换为 bool”的消息,是什么导致了问题? 我正在尝试使用我在主程序中创建的方法。
Console.WriteLine(nbOccurences);
nbOccurrences
是一个方法(顺便说一下,返回 void)。 所以编译器抱怨说“我需要在 writeline 上打印一些东西,也许你想让我打印一个 bool,但我不能将一个方法转换为一个 bool”
此外,您的nbOccurrences
似乎没有任何用处:它迭代一个数组,检查一些条件并最终增加参数值。 但是调用代码不会知道 m 值,它仍然在您的函数内部。 您应该更改返回int
方法声明(或使用out int m
参数,这不是我的选择)
这是我对您实际目标的最佳猜测:
public int nbOccurrences(int[] base1, int n)
{
int count = 0;
foreach (int i in base1)
{
if (n == 32)
{
count++;
}
}
return count;
}
static void Main(string[] args)
{
int chiffrebase = 32;
int[] test123 = new int[] { 12, 32, 33, 64, 75, 46, 42, 32 };
int occurrences = nbOccurrences(test123, chiffrebase, occurrence);
Console.WriteLine(occurrences);
}
你的方法nbOccurrences
之前没有返回任何东西,那么它怎么能用来做任何事情呢? 还有就是使用的方式out
或ref
参数来获取值通过参数从方法回来,但你不应该做的是,直到你更专家。
WriteLine
方法正在查找string
或可以转换为字符串或在其上运行ToString
内容。 相反,您给了它一个方法的名称(不是方法调用的结果,而是方法本身)。 它怎么知道如何处理它?
使用括号调用方法,因此请注意注意nbOccurrences
与nbOccurrences()
。
最后,我打赌你不需要new Program
。 它有效,但可能不是您想要的。 相反,只需调用与您正在运行的Program
相同的当前程序中的方法Program
。
最后,虽然这在您的 C# 之旅中可能还为时过早,但请注意,可以通过这种方式执行相同的任务( using System.Linq;
添加):
static void Main(string[] args)
{
int chiffrebase = 32;
int[] test123 = new int[] { 12, 32, 33, 64, 75, 46, 42, 32 };
int occurrences = test123.Count(i => i == chiffrebase);
Console.WriteLine(occrurences);
}
PS Occurrences用两个 Rs 拼写。 不是一个。
Console.WriteLine 函数有许多重载,其中之一是将 bool 作为参数。 当你调用这样的函数时
Console.WriteLine(1);
编译器确定您要调用的函数版本(在我上面的示例中,它应该是 int 版本。
在您的示例代码中,您只需要添加一些括号,如果您想调用该函数,它看起来像这样。 值得注意的是,您的 nbOccurrences 函数实际上并未返回值(它的返回类型为 void),因此这可能仍然会失败。
Console.WriteLine(nbOccurences());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.