![](/img/trans.png)
[英]Blazor CS0103: "The name 'lines' does not exist in the current context
[英]Blazor: name does not exist in current context
我收到 CS0103 错误 - “名称‘newHotel’在当前上下文中不存在”:
我创建了一个名为“Hotel”的 class,以及一个名为“HotelName”的属性。
我创建了一个名为“newHotel”的变量,它属于酒店类型。
我已经用“天堂海滩”的值初始化了变量。
@page "/hotels"
<h3>Hotels</h3>
<p>
Hotel Name: @newHotel.HotelName // **THIS IS WHERE THE ERROR IS SHOWN IN VS2019**
</p>
剩余代码:
@code {
protected override void OnInitialized()
{
base.OnInitialized();
Hotel newHotel = new Hotel
{
HotelName = "Paradise Beach"
};
}
class Hotel
{
public string HotelName { get; set; }
}
}
我不知道我哪里出错了?
非常感谢,
这是因为 newHotel 是在 OnInit 方法中声明的局部变量,所以它不在 scope 之外。 在 newHotel 的 OnInitialized 方法上方添加一个属性。
@code {
///Added property
Hotel newHotel { get; set; } = new Hotel();
protected override void OnInitialized()
{
base.OnInitialized();
newHotel = new Hotel
{
HotelName = "Paradise Beach"
};
}
class Hotel
{
public string HotelName { get; set; }
}
}
编辑:您将遇到的下一个问题是 newHotel 的 NullReference 错误,因为页面在 OnInit 方法运行和 newHotel 初始化之前尝试呈现。 一种选择是添加 null 检查 newHotel 另一种选择是在声明时对其进行初始化。
@page "/hotels"
<h3>Hotels</h3>
@if(newHotel != null)
{
<p>
Hotel Name: @newHotel.HotelName
</p>
}
我不知道这是否已经解决。 对我来说,删除“.vs”文件夹就可以了。 我实际上并不认为这是代码中的内容。 可能是 Visual Studio 在更新到新版本后出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.