开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜