我正在编写一个名为Television的类,该类具有一些简单的控件,但是我的ToString方法遇到了问题。 “'Television.ToString()':并非所有代码路径都返回值”。我将如何退回任何一条消息?感谢您的任何帮助,谢谢。
class Television
{
private string manufacturer;
private int screenSize;
private bool powerOn = false; // the power is off by default
private int channel = 2; // channel is default set to 2
private int volume = 20; // volume default set to 20
public Television (string manu, int size) // The purpose of this constructor is to initialize the manufacturer and screen size fields.
{
manufacturer = manu;
screenSize = size;
}
public int GetVolume() // accessor method that returns volume
{
return volume;
}
public int GetChannel() // accessor method that returns channel
{
return channel;
}
public string GetManufacturer() // accessor method that returns manufacturer
{
return manufacturer;
}
public int GetScreenSize() // accessor method that returns screen sizes
{
return screenSize;
}
public void SetChannel(int userChannel) // mutator method that changes the channel
{
Console.WriteLine("What channel would you like to watch?: ");
userChannel = int.Parse(Console.ReadLine());
userChannel = channel;
}
public void power() // mutator method that turns the power on/off
{
powerOn = !powerOn;
}
public void IncreaseVolume() // mutator method that increases volume by 1
{
volume = volume + 1;
}
public void DecreaseVolume() // mutator method that decreases volume by 1
{
volume = volume - 1;
}
**public string ToString()
{
if (powerOn == false) {
Console.WriteLine("A " + screenSize + " inch " + manufacturer + " has been turned off.");
}
else if (powerOn == true)
{
Console.WriteLine("A " + screenSize + " inch " + manufacturer + " has been turned on.");
}**
}
}
}
答案 0 :(得分:5)
ToString
应该重写基本方法以遵守多态设计,并且它必须返回一个字符串,但您什么也不返回:
public override string ToString()
{
string str = "A " + screenSize + " inch " + manufacturer + " has been turned ";
return str + ( powerOn ? "on." : "off." );
}
或者:
public override string ToString()
{
return $"A {screenSize} inch {manufacturer} is turned {(powerOn ? "on" : "off")}.";
}
因此您可以使用:
var television = new Television();
Console.WriteLine(television.ToString());
MessageBox.Show(television.ToString());
label.Text = television.ToString();