我已阅读docs对于 C# 可空引用类型。
我不确定如何处理框架调用我的方法的情况。
一个简单的 EF Core 示例:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfiguration(new CustomerConfiguration()); // <--- CA1062
}
这会引发警告 CA1062:
In externally visible method 'void DbContext.OnModelCreating(ModelBuilder builder)', validate parameter 'builder' is non-null before using it. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument. csharp(CA1062)
我认为框架不会向我发送 null,因此我认为检查 null 没有意义。
如何处理这种情况,即:框架使用不能为 null 的参数调用我的方法?
编辑:我的问题与链接的问题不同,因为它是通用的,并且专门询问 C# 8 的 NRT 功能。我只选择了一个相关的例子。不管怎样,感谢所有提供帮助的人。
最佳答案
根据我的评论,您可以使用 null-conditional operator ?.
仅调用 ApplyConfiguration
方法如果 builder
不是null
:
builder?.ApplyConfiguration(new CustomerConfiguration());?
来自文档:
A null-conditional operator applies a member access,
?.
, or element access,?[]
, operation to its operand only if that operand evaluates to non-null; otherwise, it returns null.
编辑以下评论中的讨论
我认为包含 OP 已经知道的替代方案是有意义的,但我将展示为更全面的解决方案。
而不是使用空条件运算符(这实际上会隐藏任何问题是 builder
实际上是 null
),只需测试 builder
在方法的开始处:
protected override void OnModelCreating(ModelBuilder builder) {
if (builder == null) throw new ArgumentNullException(nameof(builder));
base.OnModelCreating(builder);
...
这将是处理 null
的更全面的方法。值builder
因为如果您收到 null
将抛出异常进入方法。
关于c# - 当 C# 使用不能为 null 的参数调用我的方法时,避免出现警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68111301/