类构造函数:得到错误 "当前上下文中不存在名称"。

问题描述 投票:-1回答:1

我目前正在浏览一个关于类构造函数的在线课程,它给出的错误是'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'");

}
}
c# c#-4.0 overloading this class-constructors
1个回答
1
投票

你需要 biome 而不是 name 在第二个构造函数中,就像

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'");

}

在你的例子中,你是从第二个构造函数中调用第一个构造函数。当你创建 Forest 阶级只有 biome 值,然后它将调用第二个构造函数和 : this(name, "Unknown") 执行第一个构造函数。


你使用的是构造函数链,使用 this 运营商。来自MSDN

构造函数可以在同一个对象中调用另一个构造函数,通过使用 this 关键字。像基。this 可以带参数或不带参数,构造函数中的任何参数都可以作为参数使用,或者作为表达式的一部分使用。

© www.soinside.com 2019 - 2024. All rights reserved.