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"消息,导致问题的原因是什么?我试图使用我在主程序中制作的方法。
答案 0 :(得分:3)
Console.WriteLine(nbOccurences);
nbOccurrences
是一个方法(顺便说一下,返回无效)。
所以编译器抱怨说“我需要在writeline上打印一些东西,也许你想要我打印一个bool,但是我无法将一个方法转换为一个bool”
此外,您的nbOccurrences
似乎没有任何用处:它迭代一个数组,检查一些条件并最终增加参数值。但是调用代码不会知道m值,它仍然是函数内部的。您应该更改方法声明,返回int
(或使用out int m
参数,这不是我的选择)
答案 1 :(得分:2)
这是我对你实际目标的最佳猜测:
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
。
最后,虽然这可能在您的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);
}
P.S。 出现次数拼写为两个R。不是一个。
答案 2 :(得分:1)
Console.WriteLine函数有许多重载,其中一个期望bool作为参数。 当你调用这样的函数时
Console.WriteLine(1);
编译器确定要调用的函数版本(在上面的示例中,它应该是int版本。
在您的示例代码中,您只需添加一些括号,如果您想调用该函数,它就像这样。 值得注意的是,你的nbOccurrences函数实际上并没有返回一个值(它的返回类型是无效的),所以这可能仍会失败。
Console.WriteLine(nbOccurences());