在我的Blazor组件上,我正在接受一个参数。
@page "/plant/{PlantName}"
@code {
[Parameter]
public string PlantName { get; set; }
private TestGarden.Models.Plants pd = new PlantData().GetPlantInformation(PlantName);
}
在""这个方法中,我接受了一个参数GetPlantInformation
",它说为"PlantName
" - A field initializer cannot reference the non-static field, method, or property 'Plant.PlantName'
我不能把PlantName这个属性做成静态的,否则Blazor将无法工作。那么我怎样才能将这个属性作为方法参数使用呢?
投票
不知道你想做什么,但你可以使用 =>
而不是 =
// added =>
private TestGarden.Models.Plants pd => new PlantData().GetPlantInformation(PlantName);
你刚才做的事情叫做 外地初始化 并使用 =>
叫做 表达型成员 如果叫错了,请谁来纠正我)。
不同的是,当你使用 =>
,就像你在做这个
private TestGarden.Models.Plants pd
{
get
{
return new PlantData().GetPlantInformation(PlantName);
}
}
而一旦你得到 pd
,它将返回 new PlantData().GetPlantInformation(PlantName)
.
之所以使用 =
给你的错误是你不能用另一个字段的值初始化一个字段,但当使用 =>
你没有初始化它,你只会执行 new PlantData().GetPlantInformation(PlantName)
当你 pd
.
编辑。
正如其他读者所指出的,你可以使用 OnInitialized
.
但你需要了解为什么以及何时应该使用 OnInitialized
或 =>
.
你应该使用 OnInitialized
如果 new PlantData().GetPlantInformation(PlantName)
会做一些可能是异步的事情,比如从数据库中获取数据,因为如果你在一个属性的getter中调用该方法,而且需要时间,它可能会冻结你的组件,直到数据库返回值。
如果它从数据库中返回一些东西或者做一些可能是异步的事情,使用 OnInitialized
否则,就可以使用 =>
表情体)。
另外,还有一件事...
如果你使用 OnInitialized
, new PlantData().GetPlantInformation(PlantName)
将只运行一次,如果 PlantName
的值会因为某些原因发生变化。pd
不会被更新。
如果你使用 =>
,它将永远运行 new PlantData().GetPlantInformation(PlantName)
的当前值,但将始终使用 PlantName
的情况下,它有变化。
所以,有很多东西需要思考,你要如何获得价值的 new PlantData().GetPlantInformation(PlantName)
投票
Blazor组件与C#对象类似,但不一样... 该框架通过所谓的 "生命周期事件 "为创建和消费它们添加了一个语法层。
对于初始化,你必须覆盖OnInitialized()方法或其异步对应的OnInitializedAsync()方法(如果初始化需要访问一些异步数据存储)。
protected override async Task OnInitializedAsync()
{
pd = await GetPlantInformation(PlantName);
}
这个方法调用只能被调用一次,当组件被创建时。关于其他生命周期事件,请看以下内容 Blazor生命周期
投票
您不能使用非静态属性 PlantName 来初始化 TestGarden.Models.Plants 。您应该实例化TestGarden.Models.Plants来初始化它的属性,这应该在OnInitialized{Async)方法中完成。
这一点,应该在OnInitialized{Async)方法中完成。
@code {
[Parameter]
public string PlantName { get; set; }
private TestGarden.Models.Plants pd = new
PlantData().GetPlantInformation(PlantName);
}
应该这样做。
@code {
[Parameter]
public string PlantName { get; set; }
private TestGarden.Models.Plants pd;
protected override void OnInitialized()
{
pd = new PlantData().GetPlantInformation(PlantName);
}
}
注意:像这样的用法。 private Plant plant => new Plant(PlantName);
这样的用法可能会有很大的局限性,你应该小心使用,了解你所做的事情,因为它可能会导致不必要的结果。最好的方法是定义一个对象变量,然后在OnInitialized{Async)方法中实例化它。这是自然而然的方式,明晰等。