在Writeline语句中间使用方法的输出



我正在尝试从我在其他类中写的方法获取输出,以将值返回到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);
    }

百分比fruitleft是早期设置的,值为100,然后由用户类型的任何东西降低。

方法组是C#标准中使用的表达式,用于描述由其通用名称识别的一组或多种超载方法。在这种情况下,编译器指的是apple.Eatbanana.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));

这可以通过保持单个字符串一起编写的字符串模板来使您的代码更加清晰。

最新更新