C#中的对象,构造函数和重载构造函数

时间:2015-02-22 18:20:40

标签: c#

我有和程序计算x-coodinate和y-coodinate的平方。 Main.cs中的代码是

using System;
using System.Collections.Generic;
using System.Text;

namespace Classes
{
class Program
{
    static void doWork()
    {
        Point origin = new Point();//default constructor
        Point bottomRight = new Point(1366, 768);//overload constructor
        double distance = origin.DistanceTo(bottomRight);
        Console.WriteLine("Distance is:{0}", distance);
    }

    static void Main(string[] args)
    {
        try
        {
            doWork();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

和像这样的Point.cs

namespace Classes
{
class Point
{
    private int x, y;
    public Point()
    {
        //Console.WriteLine("Default constructor called");//default constructor
        this.x = -1;
        this.y = -1;
    }
    public Point(int x, int y)
    {
        //Console.WriteLine("x:{0},y:{1}", x, y);//overload constructor
        this.x = x;
        this.y = y;
    }
    public double DistanceTo(Point other)
    {
        int xDiff = this.x - other.x;//Point()-Point(int)
        int yDiff = this.y - other.y;
        double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
        return distance;
    }
}

}

但我不明白究竟是什么是this.x和this.y.

当我调试Point()或Point(int x,int y)中的哪一个用于模拟DistanceTo ??

但是我还需要更多的帮助:

双倍距离= origin.DistanceTo(bottomRight); 这段代码在做什么?什么是obj.obj ??

为什么看起来不像"双倍距离= DistanceTo(bottomRight);"

1 个答案:

答案 0 :(得分:1)

构造函数内部

public Point(int x, int y)
{
    this.x = x;
    this.y = y;
}

this.xthis.y引用类变量(private int x, y;),其中只有xy引用传递给构造函数的参数。

在方法DistanceTo() this.xthis.y中,引用x和{y的同一对象中的字段other.xother.y的值{1}}引用对象x中字段yother的值。