开发者

how to define the Console.WriteLine behavior for a class in C#?

开发者 https://www.devze.com 2023-02-05 04:33 出处:网络
I have a class: class Rect{ int x; int y; public Rect(int x, int开发者_如何学Go y){ this.x = x; this.y = y;

I have a class:

class Rect{
    int x;
    int y;
    public Rect(int x, int开发者_如何学Go y){
        this.x = x;
        this.y = y;
    }

}

I want this happen:

Console.WriteLine(new Rect(12,12));
>>> <Rect with x=12, y=12>

How could I do it?


You can override ToString() method:

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 Method (Object)

You need to override the ToString() method from Object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号