我目前正在学习有关类构造函数的在线课程。并且给出错误名称“ name”在当前上下文中不存在

class Forest
{

// first constructor
public Forest(string biome, string name)
{

  this.Name = name;
  this.Biome = biome;
  Age = 0;

}
//second constructor

public Forest(string biome) : this(name, "Unknown")
{

  Console.WriteLine("Name property not specified. Value defaulted to 'Unknown'");

}
}
评论
  • rquis
    rquis 回复

    您需要生物群系而不是名称,例如

    public Forest(string biome) : this(biome, "Unknown")
    {                  //^^^^^^ here biome is know to compiler from parameter of second constructor, not name.
    
      Console.WriteLine("Name property not specified. Value defaulted to 'Unknown'");
    
    }
    

    In your case you are calling first constructor from second constructor. When ever you create instance of Forest class with only biome value, then it will call second constructor and : this(name, "Unknown") execute first constructor and will execute code written in your first constructor.

    You are using constructor chaining using this operator. From MSDN

    一个构造函数可以通过以下方法在同一对象中调用另一个构造函数:   使用this关键字。像底座一样,无论是否使用,都可以使用   参数以及构造函数中的任何参数都可以作为   参数,或作为表达式的一部分