代码之家  ›  专栏  ›  技术社区  ›  johnny 5

Null Check运算符仍返回Null值

  •  3
  • johnny 5  · 技术社区  · 8 年前

    我试图从我的依赖注入程序中获得所有的通用服务,它实现了一个类型

    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
    }
    

    wierd的问题是,当它试图创建GenericImplements列表时,我收到了一个错误

    系统ArgumentNullException:“值不能为null。”

    enter image description here

    编辑 我怎么会用错Elvis运算符?正如你所见,s有一个值。从图片中。错误是从检查的类型生成的。这怎么可能?

    2 回复  |  直到 8 年前
        1
  •  7
  •   Sefe    8 年前

    这个 ?. 运算符仅指其应用于的解引用操作。当不只是 s 可以是 null ,但也 s.ImplementationType ,表达式。。。

    s?.ImplementationType.GetTypeInfo()
    

    ...这还不够。您需要在表达式 可以是 无效的 :

    s?.ImplementationType?.GetTypeInfo()
    

    GetTypeInfo() 不可能是 无效的 ,写下就足够了:

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

    最好不要普遍应用 ?. 对于所有解引用,但仅当值可以为null并且跳过表达式的其余部分时才使用它是可以的。如果您通常在所有情况下都应用该运算符,则可能会出现错误,否则会提前发现。

        2
  •  4
  •   Tamas Hegedus    8 年前

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

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