在下面的代码示例中,我在增量计数器演示中添加了逻辑以显示列表的内容,然后在点击事件中将“新项目”添加到列表中。但是,尽我所能尝试添加不添加...这两个 Console.WriteLine 尽职尽责地显示了添加前后三个成员的列表,但没有报告错误,列表也没有任何变化。
示例代码:
@page "/ListIncrement"
<div>
<p>Current count: @currentCount</p>
<ul>
@foreach (var ListItem in TestList)
{
<li>@ListItem</li>
}
</ul>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</div>
@code {
private int currentCount = 0;
public List<string> TestList => new List<string>{
"one", "Two", "Three" };
private void IncrementCount()
{
currentCount++;
Console.WriteLine("Count= {0}", TestList.Count);
TestList.Add("New Item");
Console.WriteLine("Count= {0}", TestList.Count);
}
}
Run Code Online (Sandbox Code Playgroud)
问题出在这一行
public List<string> TestList => new List<string>{ "one", "Two", "Three" };
Run Code Online (Sandbox Code Playgroud)
将其更改为此,它将起作用:
public List<string> TestList = new List<string>{ "one", "Two", "Three" };
Run Code Online (Sandbox Code Playgroud)
该=>
箭头被称为表达健全人组成的,它运行时TestList被称为表达,所以当组件去得到TestList,它结束了一个返回new List<string>{ "one", "Two", "Three" };
每次而不是仅在创建初始化新的列表。
以下是更多信息:https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members