【问题标题】:C# Constructor breaks due to another constructorC# 构造函数由于另一个构造函数而中断
【发布时间】:2020-11-18 03:45:00
【问题描述】:

我在库中有一个带有多个构造函数的 C# 点类(这与 .NET 中的 System.Drawing.Point 不同)。

Public class Point {

   public float X;
   public float Y;
   public float Z;

   //Constructor 1
   public Point(float x, float y, float z) {
      this.X = x;
      this.Y = y;
      this.Z = z;
   }
   //Constructor 2
   public Point(Point point) {
      this.X = point.X;
      this.Y = point.Y;
      this.Z = point.Z;
   }
   //Constructor 3
   public Point(PointF point) {
      this.X = point.X;
      this.Y = point.Y;
      this.Z = 0;
   }
   //Constructor 4
   public Point(System.Drawing.Point point) {
      this.X = point.X;
      this.Y = point.Y;
      this.Z = 0;
   }
}

当我尝试使用以float 作为参数的构造函数创建一个新的Point 对象时,一切正常。当我想使用现有的 Point 对象(构造函数 2)创建新的 Point 时,我收到一条错误消息,提示我需要引用 System.Drawing 程序集。我猜这是因为构造函数 3 和 4,因为它们将 System.Drawing.PointPointF 作为参数,但我不明白他们为什么会提出问题,因为我尝试使用的构造函数完全与它们无关,并且构造函数 1 在调用时可以正常工作。我该如何解决这个问题?谢谢!

【问题讨论】:

  • 添加对 System.Drawing 的引用?
  • 您不能使用另一个实例成员初始化一个实例成员
  • @Polyfun 这个对象在库中,我不想要求用户不必要地实现 System.Drawing。
  • @Jordan1993 你这是什么意思?在构造函数 2 中,我可以使用 Point 参数的 X、Y 和 Z 值来创建具有相同 X、Y 和 Z 值的新 Point

标签: c# class object constructor


【解决方案1】:

如果你能接受的话,有一个解决方法。

将以下内容添加到您的 Point 类中:

public static Point Clone(Point p)
{
    return new Point(p);
}

然后在当前无法编译的代码中,改为这样做:

Point p = new Point(0, 0, 0);
Point q = Point.Clone(p);

(当然,你不必调用方法Clone() - 调用它CopyCopyCtor 或任何你喜欢的。)

至于为什么,编译器坚持您必须包含对定义您甚至没有使用的类型的程序集的引用,see this answer

另见this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多