C# constructors overloading

前端 未结 3 1251
慢半拍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: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;
      }
    }
    

提交回复
热议问题