首页 > 解决方案 > 如何修复覆盖 ToString 方法

问题描述

我正在设置一个带有 GUI 的类,并且在我的代码中需要这个强制 ToString 方法时遇到问题。由于家庭紧急情况旅行,我错过了两节课,现在我对我在这里所做的事情有点迷茫。

老实说,我不太了解发生了什么,所以我正在寻找解释。但是我尝试过观看视频并在代码中移动但无济于事。

class Sandwich
{
    public string name = "Tony";
    public string meat = "None";
    public int tomatoSlices = 1;

    public override tomatoSlices.ToString()
        {
       public double ComputerPrice()
        {
              return 4.0 + (0.5 * tomatoSlices);
        }
    }
}

该程序应该运行,但不确定为什么它不运行。我想它与tomatoSlices 整数有关。

标签: c#

解决方案


如评论中所述,您已在另一个方法中声明了一个方法。您需要移动方法的ComputerPrice()外部ToString。此外,您需要tomatoSlicesToString定义中删除:

class Sandwich
{
    public string name = "Tony";
    public string meat = "None";
    public int tomatoSlices = 1;

    public double ComputerPrice()
    {
         return 4.0 + (0.5 * tomatoSlices);
    }

    public override string ToString()
    {
        return ComputerPrice().ToString();
    }
}

现在,当您调用sandwich.ToString()它时,它将以字符串的形式返回值,ComputerPrices()例如:

var sandwich = new Sandwich();

var price = sandwich.ToString();

推荐阅读