C# constructors overloading

前端 未结 3 1243
慢半拍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:10
    public Point2D(Point2D point) : this(point.X, point.Y) { }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-03 17:26

    Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

    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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题