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); } 我需要它不复制另一个构造函数的代码…
 你可以将你的通用逻辑分解为一个私有方法,例如从两个构造函数中调用的Initialize 。 
由于你想执行参数validation的事实,你不能求助于构造函数链。
例:
 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; } 
 public Point2D(Point2D point) : this(point.X, point.Y) { } 
也许你的class级不完整。 就我个人而言,我使用一个私有的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; } }