c# - 类构造函数:出现错误“名称在当前上下文中不存在”
问题描述
我目前正在学习关于类构造函数的在线课程。它给出的错误名称“名称”在当前上下文中不存在。
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'");
}
}
解决方案
您需要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 的参数,或者作为表达式的一部分
推荐阅读
- shell - 没有 -t 开关的 Docker 中的系统输出
- c# - 如何使用 dapper 执行 postgres 函数
- ios - 如何将固定高度视图添加到垂直堆栈视图?
- sql-server - 根据 sql 查询中可用的记录数在 Userform 上创建多个复选框
- android - 如何像 Android 中的 uber 一样在地图上为我的汽车设置动画和旋转?
- bash - 如何在多次出现某些字符后删除整个字符串?
- python - python数据框根据行数对行进行分组
- python - 如何使用带有多重分隔符的 df.str.split() 来保留分隔符
- php - 如何使用“Tink”在客户端(Android)加密并在服务器端(PHP)解密
- r - 动态列名似乎在使用 := 时有效,但在 data.table 中使用 = 时无效