Kyl*_*yle 12 c# blazor blazor-server-side
如果我打开了可为 null 的引用类型,那么在 Blazor 中使用 @ref 引用时避免出现警告的最佳实践是什么?
例子:
<Modal @ref="addModal"></Model>
private Modal addModal;
将产生:
CS8618 Non-nullable field 'addModal' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.
和
CS8625 Cannot convert null literal to non-nullable reference type.
如果我尝试初始化它,如下所示:
private Modal addModal = new Modal()
我仍然得到:
CS8625 Cannot convert null literal to non-nullable reference type.
我可以使引用可为空,如下所示:
private Modal? addModal;
但是每次使用它时我都需要进行空检查以避免警告,即使它实际上不可能为空。
小智 18
用[AllowNull]装饰- 这将消除剃刀上烦人的警告。这适用于 VS 17.4.1 ...不知道以前或未来的版本。
[AllowNull]
private Modal addModal;
Run Code Online (Sandbox Code Playgroud)
就我而言,我使用一个单独的文件来保留我的代码。我遇到了同样的问题。 private MudDropContainer<DropItem> container = default!;
专门针对代码隐藏文件工作,但在使用@ref="@container"
.
最终我最终做到了这一点,private MudDropContainer<DropItem>? container = default!;
而且确实有效。但我怀疑这个问题与剃须刀设计者更相关,并且可能会在以后的版本中得到解决。
您可以告诉编译器您知道该对象不会为空,如下所示......
private Model addModel = null!;
Run Code Online (Sandbox Code Playgroud)
这会禁用警告。