2015-06-22 62 views
1

我是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; 
    } 
} 
+2

看看你行類的定義。沒有後備變量.... –

+1

'static void Line(Point pointA,Point pointB)'不是構造函數。將'static void'改爲'public'。 –

+0

您還沒有爲'Line'定義任何構造函數。所以它只有一個沒有參數的默認值。因此,沒有兩個參數的構造函數。它也沒有叫'bottomRight'或'origin'的成員,所以你不能訪問不存在的成員。 – David

回答

1

不要使用空

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

public,not Public – voytek

+0

感謝您的支持 –

+0

我修正了構造函數的問題,用「public」去掉了「static void」,但現在我遇到了GetLength方法的問題。我無法獲得該方法來識別Line myLine對象,bottomRight和origin中的兩個變量。我怎樣才能訪問這些? – shampouya

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.BottomRightline.OriginGetLength方法:

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

這應該工作現在

+0

工作了,謝謝! – shampouya

+0

@shampouya不客氣:)但你應該考慮接受答案,而不是評論。看着你的個人資料,我不確定你是否瞭解這種做法:) – voytek

相關問題