请C#大神看下,为什么必须重写ToString()方法才能正确输出Red
namespacesanliebiao{classProgram{staticvoidMain(string[]args){Colorred=newColor("Red"...
namespace sanliebiao
{
class Program
{
static void Main(string[] args)
{
Color red = new Color("Red", 255, 0, 0);
Console.Write(red);
}
}
请问重写的ToString()方法没用到,怎么影响到输出了呢?代码如下:
class Color
{
public string Name;
public int R;
public int G;
public int B;
public Color(string name,int red,int green,int blue)
{
Name = name;
G = green;
R = red;
B = blue;
}
public override string ToString()
{
return Name + "\nR=" + R + "\nG=" + G + "\nB=" + B + "\n";
}
}
}
中间的文字去掉就是完整的代码 展开
{
class Program
{
static void Main(string[] args)
{
Color red = new Color("Red", 255, 0, 0);
Console.Write(red);
}
}
请问重写的ToString()方法没用到,怎么影响到输出了呢?代码如下:
class Color
{
public string Name;
public int R;
public int G;
public int B;
public Color(string name,int red,int green,int blue)
{
Name = name;
G = green;
R = red;
B = blue;
}
public override string ToString()
{
return Name + "\nR=" + R + "\nG=" + G + "\nB=" + B + "\n";
}
}
}
中间的文字去掉就是完整的代码 展开
展开全部
Console.Write(red)相当于Console.Write(red.ToString()),任何对象在用作输出时,或者与字符串做连接时,都会自动调用ToString方法,比如说
string str = red + "hello";//相当于string str = red.ToString()+ "hello";
Console.Write(str);
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询