[英]C# constructors overloading
我如何在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);
}
我需要它不要从另一个构造函数复制代码...
public Point2D(Point2D point) : this(point.X, point.Y) { }
您可以将您的公共逻辑分解为私有方法,例如,从两个构造函数调用的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;
}
也许你的班级不完整。 就个人而言,我使用私有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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.