2011-04-05 119 views
52

如何使用構造函數在C#這樣的:C#構造函數重載

public Point2D(double x, double y) 
{ 
    // ... Contracts ... 

    X = x; 
    Y = y; 
} 

public Point2D(Point2D point) 
{ 
    if (point == null) 
     ArgumentNullException("point"); 
    Contract.EndContractsBlock(); 

    this(point.X, point.Y); 
} 

我需要它不是從另一個構造複製代碼...

回答

55

你可以將你常用的邏輯轉換爲私有方法,例如調用Initialize,該方法從兩個構造函數中調用。

由於您希望執行參數驗證,因此您無法訴諸構造函數鏈接。

例子:

public Point2D(double x, double y) 
{ 
    // Contracts 

    Initialize(x, y); 
} 

public Point2D(Point2D point) 
{ 
    if (point == null) 
     throw new ArgumentNullException("point"); 

    // Contracts 

    Initialize(point.X, point.Y); 
} 

private void Initialize(double x, double y) 
{ 
    X = x; 
    Y = y; 
} 
+13

作爲一個不變性的狂熱粉絲,我想指出這種方法的一個缺點是你不能初始化只讀字段:( – 2011-04-05 17:28:27

+0

我在想這個完全相同的解決方案,現在你確認這是一個好主意。謝謝: ) – superiggy 2013-03-23 01:12:41

+6

先嚐試Mark Cidade的回答。使用這個作爲後備。 – gidmanma 2013-09-04 15:35:37

144
public Point2D(Point2D point) : this(point.X, point.Y) { } 
+0

我想利用合同與空異常,如果點是空 – 2011-04-05 17:15:06

+4

點不能爲空,因爲它沒有被定義爲可空類型(的Point2D?點) – RvdK 2011-04-05 17:16:48

+0

描述你使用合同的意思。馬克的回答是對的。 – SQLMason 2011-04-05 17:17:26

5

也許你的類是不夠全面。就我個人而言,我使用私有的init()函數來處理所有重載的構造函數。

class Point2D { 

    double X, Y; 

    public Point2D(double x, double y) { 
    init(x, y); 
    } 

    public Point2D(Point2D point) { 
    if (point == null) 
     throw new ArgumentNullException("point"); 
    init(point.X, point.Y); 
    } 

    void init(double x, double y) { 
    // ... Contracts ... 
    X = x; 
    Y = y; 
    } 
}