繁体   English   中英

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

[英]object in C#, constructor and overload constructor

我有程序计算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?

为什么它看起来不像是“ double distance = DistanceTo(bottomRight);”;

内部构造函数

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

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

在方法DistanceTo() this.xthis.y指字段的值xy在相同的对象,其中other.xother.y指字段的值xy在对象other

暂无
暂无

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

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