我是C#的新手,我正在學習範圍。只需製作一個簡單的程序即可基於該行中兩個端點的座標計算一條線的長度。在下面代碼的第7行中,我得到一個編譯器錯誤,說Line類的構造函數不能帶兩個參數。這是爲什麼?然後在第30行和第31行左右,我無法使GetLength方法識別bottomRight點和原點。任何意見將不勝感激,謝謝!爲什麼我不能在C#中用兩個參數調用這個構造函數?
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;
}
}
看看你行類的定義。沒有後備變量.... –
'static void Line(Point pointA,Point pointB)'不是構造函數。將'static void'改爲'public'。 –
您還沒有爲'Line'定義任何構造函數。所以它只有一個沒有參數的默認值。因此,沒有兩個參數的構造函數。它也沒有叫'bottomRight'或'origin'的成員,所以你不能訪問不存在的成員。 – David