[英]how to define the Console.WriteLine behavior for a class in C#?
我有一节课:
class Rect{
int x;
int y;
public Rect(int x, int y){
this.x = x;
this.y = y;
}
}
我希望这种情况发生:
Console.WriteLine(new Rect(12,12));
>>> <Rect with x=12, y=12>
我怎么能这样做?
您可以覆盖ToString()
方法:
class Rect{
int x;
int y;
public Rect(int x, int y){
this.x = x;
this.y = y;
}
public override string ToString()
{
return "("+x.ToString()+","+y.ToString()+")";
}
}
您需要从Object
重写ToString()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.