将空文字或可能的空值转换为不可为空的类型

335*_*307 2 c# .net-core

是否可以解决此警告:

将空文字或可能的空值转换为不可为空的类型。

不抑制此 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.

                   
                }
            }
Run Code Online (Sandbox Code Playgroud)

使用反射。

在此处输入图片说明

我使用的是 Visual Studio 2019 和 .NET Core 3.1。

Cod*_*ter 11

Find()null找不到您要查找的内容时可以返回。所以destinationProperty可以变为空。

因此,解决方案是将其声明为可为空的:

PropertyInfo? destinationProperty = ...
Run Code Online (Sandbox Code Playgroud)

或者抛出异常:

PropertyInfo destinationProperty = ...Find() ?? throw new ArgumentException(...)
Run Code Online (Sandbox Code Playgroud)

  • 如果 PropertyInfo 是一个类,则它允许空值。所以,我不明白为什么需要它。更明确的代码? (5认同)
  • @Carlos 此编译器警告是从可为 null 的上下文发出的,请参阅 https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references#nullable-contexts。编译器警告 OP 的变量被声明为不可空(“PropertyInfo destinationProperty”缺少“?”),但“Find()”方法可以返回空值。这是 C# 8 的一项功能。 (2认同)