簡體   English   中英

將 null 文字或可能的 null 值轉換為不可空類型

[英]Converting null literal or possible null value to non-nullable type

是否可以解決此警告:

將 null 文字或可能的 null 值轉換為不可空類型。

沒有抑制此 C# 代碼

 List<PropertyInfo> sourceProperties = sourceObject.GetType().GetProperties().ToList<PropertyInfo>();
            List<PropertyInfo> destinationProperties = destinationObject.GetType().GetProperties().ToList<PropertyInfo>();

            foreach (PropertyInfo sourceProperty in sourceProperties)
            {
                if (!Equals(destinationProperties, null))
                {
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
                    PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.

                   
                }
            }

使用反射。

在此處輸入圖像描述

我正在使用 Visual Studio 2019 和 .NET Core 3.1。

當找不到您要查找的內容時, Find()可以返回null 所以destinationProperty可以變成null。

所以解決方案是將其聲明為可為空的:

PropertyInfo? destinationProperty = ...

或者拋出異常:

PropertyInfo destinationProperty = ...Find() ?? throw new ArgumentException(...)

您可以采用@codecaster 提出的解決方案之一,或者如Microsoft 文檔所述,您也可以通過添加 null 寬容運算符來禁用此警告, ! 到右邊

PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name)!; //<------ note the "!" operator at the endo of the line

你可以做一件事,而不是使用類型 'PropertyInfo' PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);

您可以使用 'var' var destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM