繁体   English   中英

如何在C#中为类定义Console.WriteLine行为?

[英]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()+")";
    }

}

Console.WriteLine方法(对象)

您需要从Object重写ToString()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM