c# - 如何修复覆盖 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 整数有关。
解决方案
如评论中所述,您已在另一个方法中声明了一个方法。您需要移动方法的ComputerPrice()
外部ToString
。此外,您需要tomatoSlices
从ToString
定义中删除:
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();
推荐阅读
- python - 熊猫日期格式
- c# - 在 ASP.NET Core Web Api 中使用 JWT 授权检查 IP
- selenium-webdriver - 使用带有 Sendkeys 的动作类(“15/16”)后如何释放键
- android - 向 Okhttp 发送不同格式的 json
- amazon-web-services - 使用 root 用户(= 存储桶所有者)将存储桶策略放在 aws s3 存储桶上时访问被拒绝
- uwp - 如何在 UWP 中旋转 Textblock 后获得正确的宽度和高度
- html - 用内容扩展 div 宽度
- java - Levenshtein 算法中的缺失值和 NPE
- .net - 多个网站平台上的 GTM 和 GA 跟踪
- outlook - 为所有日历启用 Cloud Elements Microsoft Graph 日历 webhook 很热门吗?