首页 > 解决方案 > 类构造函数:出现错误“名称在当前上下文中不存在”

问题描述

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

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.0overloadingthisclass-constructors

解决方案


您需要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构造函数可以使用关键字调用同一对象中的另一个构造函数。和 base 一样,this可以带参数也可以不带参数,构造函数中的任何参数都可以作为 this 的参数,或者作为表达式的一部分


推荐阅读