【发布时间】:2021-01-27 04:30:59
【问题描述】:
我是 Blazor 的初学者,正在制作一个简单的待办事项列表项目。添加列表时出现错误。 未处理的异常渲染组件:对象引用未设置为对象的实例。
System.NullReferenceException: Object reference not set to an instance of an object.
at FrontEnd.Pages.Index.AddList(KeyboardEventArgs e) in C:\Users\bryan\source\repos\Productivity_App\FrontEnd\Pages\Index.razor.cs:line 20
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
我尝试搜索问题并找到了类似的帖子here,但答案对我没有帮助,看着问题。我认为修复它与 blazor 生命周期有关。这是与错误相关的代码。
Index.razor
<div class="toDoList">
@if (ToDoListCollection != null)
{
@foreach (string toDoList in ToDoListCollection)
{
<input type="checkbox" id="checkbox">
<label for="checkbox">@toDoList</label>
<hr />
}
}
else
{}
</div>
Index.razor.cs
namespace FrontEnd.Pages
{
public partial class Index
{
public bool IsCompleted { get; set; }
public string Description { get; set; }
public List<string> ToDoListCollection { get; set; }
public void AddList(KeyboardEventArgs e)
{
if (e.Key == "Enter" && !string.IsNullOrWhiteSpace(Description) ||
e.Key == "NumpadEnter" && !string.IsNullOrWhiteSpace(Description))
{
ToDoListCollection.Add($"{Description}"); // This is the line that the error message is referencing
Description = null;
} else
{}
}
【问题讨论】:
-
集合初始化了吗?在您提供的代码中,我没有看到任何类似于
ToDoListCollection = new List<string>()的内容
标签: c# blazor blazor-webassembly