gpt4 book ai didi

c# - Null Check Operator 仍然返回空值

转载 作者:行者123 更新时间:2023-11-30 13:29:53 25 4
gpt4 key购买 nike

我正在尝试从实现类型的依赖注入(inject)器获取所有通用服务

protected List<ServiceDescriptor> GetGenericServicesFromGenericTypeDefinition(IServiceCollection services, Type baseGenericTypeDefinition)
{
if(false == baseGenericTypeDefinition.IsGenericTypeDefinition)
{
throw new Exception($"Invalid Argument {nameof(baseGenericTypeDefinition)}");
}

//TODO: check the base type recursively
var genericImplementations = services.Where(s => s?.ImplementationType.GetTypeInfo().IsGenericType ?? false)
.ToList();
//.... Omitted unrelated to issue
}

奇怪的是,当它尝试创建 genericImplementations 列表时,我收到一个错误

System.ArgumentNullException: 'Value cannot be null.'

我已经检查过它不是 null 的服务,但是实现类型是。这怎么可能,这与 func 的构造方式有什么关系吗? enter image description here

编辑我怎么用错了猫王运算符?如您所见,s 具有一个值。从图片。错误是从检查的类型生成的,这怎么可能?

最佳答案

?. 运算符仅引用它所应用的取消引用操作。当不仅 s 可以为 null,而且 s.ImplementationType 时,表达式...

s?.ImplementationType.GetTypeInfo()

...还不够。您需要在表达式 左边 可以是 null 的所有地方使用运算符:

s?.ImplementationType?.GetTypeInfo()

由于GetTypeInfo()的返回值不能为null,所以写成:

s?.ImplementationType?.GetTypeInfo().IsGenericType ?? false

最好不要将 ?. 通常应用于所有取消引用,而是仅在值可能为 null 时才使用它并且跳过表达式的其余部分就可以了。如果您在所有情况下都普遍应用运算符,则错误可能会漏掉,否则会被及早发现。

关于c# - Null Check Operator 仍然返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47594652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com