Ale*_*kov 62 c# constructor constructor-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);
}
Run Code Online (Sandbox Code Playgroud)
我需要它不要从另一个构造函数复制代码...
Mar*_*ade 179
public Point2D(Point2D point) : this(point.X, point.Y) { }
Run Code Online (Sandbox Code Playgroud)
Joã*_*elo 61
您可以将您的公共逻辑分解为私有方法,例如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;
}
Run Code Online (Sandbox Code Playgroud)
也许你的班级不完整.就个人而言,我使用私有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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
99140 次 |
最近记录: |