C# constructors overloading

前端 未结 3 1247
慢半拍i
慢半拍i 2020-12-03 16:45

How I can use constructors in C# like this:

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

    X = x;
    Y = y;
}

public Point2D(Point2D po         


        
3条回答
  •  庸人自扰
    2020-12-03 17:16

    You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

    Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

    Example:

    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;
    }
    

提交回复
热议问题