我试图从我在另一个类中编写的方法获取输出,以将值返回到writeline语句的中间。错误“运算符'+'不能应用于'字符串'和'方法组'类型的操作数是阻止任何运行,但我似乎无法找到解决错误。这可能是一个我想念的真正简单的事情,但我仍然是编程的新手,所以我可能会遗漏一些明显的东西。
public void EatFruits()
{
double dblpercent;
this.MakeFruits();
Console.WriteLine("You have an Apple and a Banana in your fruit garden.");
Console.WriteLine("What Percent of the Apple would you like to eat?");
dblpercent = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("What Percent of the Banana would you like to eat?");
dblpercent = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You have " + (apple.Eat) + "% of your apple and " + (banana.Eat) + "% of your banana left.");
}
另一个类中的Eat方法的代码是:
public double Eat(double dblpercent)
{
return (PercentFruitLeft-dblpercent);
}
PercentFruitLeft早期设置为100,然后根据用户输入的数量减少他们想要吃多少。
答案 0 :(得分:1)
方法组是C#标准中使用的表达式,用于描述由其通用名称标识的一组一个或多个重载方法。在这种情况下,编译器引用apple.Eat
和banana.Eat
方法组。
您需要在方法名称后面的括号中使用参数调用您的方法。此外,对于苹果和香蕉,您需要单独的dblpercent
变量:
Console.WriteLine("What Percent of the Apple would you like to eat?");
double dblpercentApple = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("What Percent of the Banana would you like to eat?");
double dblpercentBanana = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You have " + (apple.Eat(dblpercentApple)) + "% of your apple and " + (banana.Eat(dblpercentBanana)) + "% of your banana left.");
您可以使用格式化,而不是使用连接手动编写字符串,如下所示:
Console.WriteLine("You have {0}"% of your apple and {1}% of your banana left.", apple.Eat(dblpercentApple), banana.Eat(dblpercentBanana));
通过将您一起编写的字符串模板保存在一个字符串中,可以使代码更加清晰。