簡體   English   中英

空檢查運算符仍返回空值

[英]Null Check Operator still returns a null value

我正在嘗試從我的依賴注入器獲取實現類型的所有通用服務

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 List時,我收到一個錯誤

System.ArgumentNullException:'值不能為空。'

我檢查了它不是null的服務,但是實現類型。 這怎么可能,這有些與func如何構建有關? 在此輸入圖像描述

編輯我如何使用Elvis操作員錯誤? 你可以看到s有一個值。 從圖片。 錯誤是從檢查的類型生成的,這怎么可能?

?. operator僅指它應用的解除引用操作。 當不僅s可以為null ,而且s.ImplementationType ,表達式......

s?.ImplementationType.GetTypeInfo()

......還不夠。 您需要在左側表達式 null所有位置使用運算符:

s?.ImplementationType?.GetTypeInfo()

由於GetTypeInfo()的返回不能為null ,因此寫入:

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

不通常應用?.是一個好主意?. 對所有解除引用,但僅在值可以為null並且跳過表達式的其余部分時才使用它是正常的。 如果您通常在所有情況下都應用操作員,則可能會出現錯誤,否則會很早發現錯誤。

您必須在每個成員訪問和成員調用時使用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