简体   繁体   English

Blazor:名称在当前上下文中不存在

[英]Blazor: name does not exist in current context

I am receiving an error of CS0103 - 'The name 'newHotel' does not exist in the current context':我收到 CS0103 错误 - “名称‘newHotel’在当前上下文中不存在”:

I've created a class called 'Hotel', and a property called 'HotelName'.我创建了一个名为“Hotel”的 class,以及一个名为“HotelName”的属性。
I've created a variable called 'newHotel', which is of type Hotel.我创建了一个名为“newHotel”的变量,它属于酒店类型。
And I have initialised the variable with a value of "Paradise Beach".我已经用“天堂海滩”的值初始化了变量。

@page "/hotels"


<h3>Hotels</h3>
<p>
    Hotel Name: @newHotel.HotelName // **THIS IS WHERE THE ERROR IS SHOWN IN VS2019**
</p>

Remaining code:剩余代码:

@code {

    protected override void OnInitialized()
    {
        base.OnInitialized();

        Hotel newHotel = new Hotel 
        {
            HotelName = "Paradise Beach"
        };
    }

    class Hotel
    {
        public string HotelName { get; set; }
    }
}

I can't tell where I am going wrong?我不知道我哪里出错了?

Many thanks,非常感谢,

It is because newHotel is a local variable declared in the OnInit method so it is out of scope.这是因为 newHotel 是在 OnInit 方法中声明的局部变量,所以它不在 scope 之外。 Add a property above the OnInitialized method for newHotel.在 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; }
    }
}

Edit: The next issue you will encounter is a NullReference error for newHotel due to the page trying to render before the OnInit method runs and newHotel is initialized.编辑:您将遇到的下一个问题是 newHotel 的 NullReference 错误,因为页面在 OnInit 方法运行和 newHotel 初始化之前尝试呈现。 One option is to add a null check for newHotel another option is to initialize it when it is being declared.一种选择是添加 null 检查 newHotel 另一种选择是在声明时对其进行初始化。


@page "/hotels"


<h3>Hotels</h3>

@if(newHotel != null)
{
<p>
    Hotel Name: @newHotel.HotelName
</p>
}

I don't know if this has been resolved or not.我不知道这是否已经解决。 For me, deleting the '.vs' folder did the trick.对我来说,删除“.vs”文件夹就可以了。 I don't actually think it's something in the code.我实际上并不认为这是代码中的内容。 It might be that Visual Studio acts up after updating to new versions.可能是 Visual Studio 在更新到新版本后出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM