【问题标题】:How to reference another constructor? [duplicate]如何引用另一个构造函数? [复制]
【发布时间】:2016-09-19 20:24:33
【问题描述】:

如何在c#中引用另一个构造函数?例如

class A
{
    A(int x, int y) {}

    A(int[] point)
    {
      how to call A(point.x, point.y}?
    )
}

【问题讨论】:

  • 可以在构造函数中使用keyword this

标签: c# constructor


【解决方案1】:

这很简单。与调用基本构造函数的方式相同。

A(int[] point) : this(point[0], point[1])
{
}

【讨论】:

  • 这不是base 构造函数。
  • 我从没说过?
  • 啊,对不起。我看错了。
【解决方案2】:

您可以在“派生”构造函数中使用关键字this 来调用“this”构造函数:

class A
{
    A(int x, int y) {}

    A(int[] point) : this(point[0], point[1]) { //using this to refer to its own class constructor
    {

    }    
}

除此之外,我认为您应该通过索引获取数组中的值:point[0], point[1],而不是像获取字段/属性那样做:point.x, point.y

【讨论】:

  • 不,那是 this 构造函数,而不是 base 构造函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-27
  • 2015-07-02
  • 2017-01-05
  • 2021-07-09
  • 2010-09-22
相关资源
最近更新 更多