【问题标题】:How can you use constructor chaining while :base() exist?:base() 存在时如何使用构造函数链接?
【发布时间】:2017-02-16 08:16:47
【问题描述】:

Square上的构造函数需要设置自己的参数,并且该参数继承自父类Polygon。

class Polygon
{
    public int NumSides;

    public Polygon(int numSides)
    {
        NumSides = numSides;
    }
}

class Square : Polygon 
{

    public int SideLength; 

    public Square (int sideLength) : this(numSides) : base(numSides)
    {
        SideLength = sidelength; 
        NumSides = NumSides; 
    }
}

【问题讨论】:

  • NumSides = NumSides; 是什么意思?
  • 您想知道如何调用基本构造函数吗?
  • NumSides = 边数。
  • : this(numSides)Square 中的作用是什么?在该位置使用this 通常用于调用不同的构造函数 - 但这似乎是在尝试调用 same 构造函数,即使它有效也会产生堆栈溢出。
  • 不清楚你的问题是什么。 Square 类的构造函数不正确。 this(numSides) 一遍又一遍地调用自己,永远不会跳出那个循环。我将进入无限循环并与 StackOverFlowException 中断。

标签: c# oop c#-4.0


【解决方案1】:
public Square (int sideLength) 
        //: this(numSides)   // would call this ctor again, an endless loop
          : base(4)          // because a square has 4 sides
{
    SideLength = sidelength; 
    // NumSides = NumSides;  // action already taken in the base class
}

【讨论】:

    【解决方案2】:

    要传递给基类的参数必须是子类的ctor的一部分:

    class Square : Polygon {
    
        public int SideLength; 
    
        public Square (int sideLength, int numSides) : base(numSides) {
            SideLength = sidelength; 
            // NumSides will be handled by base class ctor
        }
    
        // ctor overload with fixed number of sides for squares
        public Square (int sideLength) : this(sideLength, 4) {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      相关资源
      最近更新 更多