【问题标题】:Point point = null as default parameter in class constructorPoint point = null 作为类构造函数中的默认参数
【发布时间】:2014-04-26 10:35:21
【问题描述】:

当我尝试编译这个简单的代码时,我的构造函数中出现了两个错误:“类型的值不能用作默认参数” 我该如何解决这个问题?

  public class PointerArgs
  {

      public Point Point { get; set; }


      public Point TransformedPoint { get; set; }


      public PointerArgs(Point point = null, Point transformedPoint = null)
      {
          this.Point = point;
          this.TransformedPoint = transformedPoint;
      }
  }

【问题讨论】:

标签: c# .net


【解决方案1】:

您不能将Point 设置为null,因为它是值类型。

这样做:

public PointerArgs(Point point = default(Point), Point transformedPoint = default(Point))
{
   this.Point = point;
   this.TransformedPoint = transformedPoint;
}

您可以通过将其设为Nullable 类型将其分配为空,但这在这里是不必要的。

【讨论】:

  • ..您可能也需要对其他可选值类型参数执行此操作..
  • 现在您已将其设为可空,它不能分配给不可为空的类级别属性。
  • @SimonWhitehead 我应该把它留给default(Point)吗?
  • 没问题。感谢您没有将我的建议视为侮辱......很多人似乎都在这样做:) +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
相关资源
最近更新 更多