![](/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.