AutoMapping:取消引用可能为空的引用吗?空条件运算符不适用于自动映射

问题描述 投票:2回答:2

我将AutoMapper用于类AB。该项目是带有<Nullable>enabled</Nullable>的.Net核心项目。

public class A 
{
    public ClassX? X { get; set; } // ClassX is a custom class with the property of Value.
    //.... 
}

public class B 
{
    public string? X { get; set; } 
   // ....
}

在下面的映射代码中

public void Mapping(Profile profile)
{
    // ....

    _ = profile?.CreateMap<A, B>()
        .ForMember(d => d.X, o => o.MapFrom(s => s.X.Value)); // warning on s.X
}

它在s.X上显示以下警告:

警告CS8602取消引用可能为空的引用。

如何在不使用#pragma warning disable CS8602的情况下消除警告?

我尝试使用空条件将o.MapFrom(s => s.X.Value)更改为o.MapFrom(s => s.X?.Value)。但是它在s.X?.Value上显示以下错误

错误CS8072表达式树lambda可能不包含空传播运算符

c# automapper
2个回答
2
投票

使用空条件运算符:

_ = profile?.CreateMap<A, B>()
    .ForMember(d => d.X, o => o.MapFrom(s => s.X?.Value));

根据您的声明,属性X可为空。因此,必须确保它为null时不会被取消引用。如果s.X为null,则s.X?.Value将返回null而不是访问Value

表达式等于s.X == null ? null : s.X.Value

((根据@Attersson)如果要在空情况下分配其他值,则可以将空合并运算符与空条件运算符结合使用:s.X?.Value ?? someDefaultValue


-3
投票

您可以将[NotNull]放在方法的参数中

public void Mapping([NotNull] Profile profile)

更多信息在这里

https://www.meziantou.net/csharp-8-nullable-reference-types.htm

否则您可以使用??操作员检查。

 _ = profile?.CreateMap<A, B>()
    .ForMember(d => d.X, o => o.MapFrom(s => s.X.Value ?? string.Empty )); 
© www.soinside.com 2019 - 2024. All rights reserved.