1

我试图从我在不同类中编写的方法获取输出,以将值返回到 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,然后根据用户输入的想要吃多少来减少。

4

1 回答 1

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));

通过将您一起编写的字符串模板保留在单个字符串中,这使您的代码更加清晰。

于 2012-11-10T02:32:04.957 回答