是否可以解决此警告:
将空文字或可能的空值转换为不可为空的类型。
不抑制此 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)
| 归档时间: |
|
| 查看次数: |
2933 次 |
| 最近记录: |