为什么我不能在C#中用两个参数调用这个构造函数?

时间:2015-06-22 00:30:58

标签: c#

我是C#的新手,我正在学习范围。只需制作一个简单的程序,根据行中两个端点的坐标计算一条线的长度。在下面的代码的第7行中,我收到一个编译器错误,指出Line类的构造函数不能接受两个参数。这是为什么?然后在第30和31行左右,我无法获得GetLength方法来识别bottomRight点和原点。任何建议都将不胜感激,谢谢!

class Program
{
    static void doWork()
    {
        Point origin = new Point(0,0);
        Point bottomRight = new Point(1366, 768);
        Line myLine = new Line(bottomRight, origin);
        //double distance = origin.DistanceTo(bottomRight);
        double distance = GetLength(myLine);
        Console.WriteLine("Distance is: {0}", distance);
        Console.WriteLine("Number of Point objects: {0}", Point.ObjectCount());
        Console.ReadLine();
    }

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

    static double GetLength(Line line)
    {
        Point pointA = line.bottomRight;
        Point pointB = line.origin;
        return pointA.DistanceTo(pointB);
    }

}

class Line
{

    static void Line(Point pointA, Point pointB)
    {
        pointA = new Point();
        pointB = new Point();
    }
}

以下是Point类的代码:

class Point
{
    private int x, y;
    private static int objectCount = 0;

    public Point()
    {
        this.x = -1;
        this.y = -1;
        objectCount++;
    }

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

    public double DistanceTo(Point other)
    {
        int xDiff = this.x - other.x;
        int yDiff = this.y - other.y;
        double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
        return distance;
    }

    public static int ObjectCount()
    {
        return objectCount;
    }
}

2 个答案:

答案 0 :(得分:1)

不要使用void

 public Line(Point pointA, Point pointB)
    {
        pointA = new Point();
        pointB = new Point();
    }

答案 1 :(得分:0)

您的Line课程看起来不完整。它不存储任何数据。看起来应该更像这样:

class Line
{
    public Point BottomRight { get; set; }
    public Point Origin { get; set; }

    public Line(Point pointA, Point pointB)
    {
        Origin = pointA;
        BottomRight = pointB;
    }
}

然后您只需要在line.BottomRight方法中更改line.OriginGetLength

    static double GetLength(Line line)
    {
        Point pointA = line.BottomRight;
        Point pointB = line.Origin;
        return pointA.DistanceTo(pointB);
    }

这应该现在可以使用