简体   繁体   English

空检查运算符仍返回空值

[英]Null Check Operator still returns a null value

I'm trying to get all of the generic service from my dependency injector who implement a type 我正在尝试从我的依赖注入器获取实现类型的所有通用服务

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
}

The wierd thing is that when it tries to create genericImplementations List I receive an Error 奇怪的是,当它试图创建genericImplementations List时,我收到一个错误

System.ArgumentNullException: 'Value cannot be null.' System.ArgumentNullException:'值不能为空。'

I've checked the service it is not null, the Implementation type is however. 我检查了它不是null的服务,但是实现类型。 How is this possible, Is this some how related to how the func is constructed? 这怎么可能,这有些与func如何构建有关? 在此输入图像描述

EDIT How am I using the Elvis Operator wrong? 编辑我如何使用Elvis操作员错误? s has a value as you can see. 你可以看到s有一个值。 from the picture. 从图片。 The error is generating from the type checked how is this possible? 错误是从检查的类型生成的,这怎么可能?

The ?. ?. operator refers only to the dereferencing operation it is applied to. operator仅指它应用的解除引用操作。 When not only s can be null , but also s.ImplementationType , the expression... 当不仅s可以为null ,而且s.ImplementationType ,表达式......

s?.ImplementationType.GetTypeInfo()

...won't be enough. ......还不够。 You need to use the operator in all places where the expression to the left can be null : 您需要在左侧表达式 null所有位置使用运算符:

s?.ImplementationType?.GetTypeInfo()

Since the return of GetTypeInfo() can not be null , it is enough to write: 由于GetTypeInfo()的返回不能为null ,因此写入:

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

It's a good idea not to generally apply the ?. 不通常应用?.是一个好主意?. to all dereferences, but to use it only when the value could be null and skipping the rest of the expression is OK. 对所有解除引用,但仅在值可以为null并且跳过表达式的其余部分时才使用它是正常的。 If you apply the operator generally in all cases, errors might fall through that otherwise would get caught early. 如果您通常在所有情况下都应用操作员,则可能会出现错误,否则会很早发现错误。

您必须在每个成员访问和成员调用时使用null检查运算符来传播任何级别的空值,如下所示:

var genericImplementations = services.Where(s => s?.ImplementationType?.GetTypeInfo()?.IsGenericType ?? false).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM