【问题标题】:AutoMapping: Dereference of a possibly null reference? Null-conditional operator doesn't work with AutoMappingAutoMapping:取消引用可能为空的引用?空条件运算符不适用于 AutoMapping
【发布时间】:2020-04-16 20:15:05
【问题描述】:

我将 AutoMapper 用于 AB 类。该项目是一个 .Net 核心项目,<Nullable>enabled</Nullable>

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的情况下摆脱警告?

我尝试使用 Null 条件将 o.MapFrom(s =&gt; s.X.Value) 更改为 o.MapFrom(s =&gt; s.X?.Value)。但它在s.X?.Value 上出现以下错误

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

【问题讨论】:

  • 我已经删除了 CS8602,这个警告它的可怕甚至特定的警卫(例如 Guard/Ensure fail early)都被忽略了,而且需要大量的条件,因为它无法分辨。然后它会导致代码被污染/更难阅读并且人们浪费时间。

标签: c# automapper


【解决方案1】:

由于MapFrom 接受Expression&lt;&gt; 而不是Func&lt;&gt;,因此您不能使用空条件运算符。这不是 AutoMapper 的限制,而是 System.Linq.Expressions 命名空间中的表达式树和 C# 编译器的限制。

但是,您可以使用三元运算符:

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

根据您的声明,X 属性可以为空。因此,您必须确保它为 null 时不会被取消引用。

(根据@Attersson)如果你想在 null 情况下分配不同的值,你可以结合使用 null-coalescing 运算符和三元运算符:

(s.X == null ? someDefaultValue : s.X.Value)

// e.g for string
(s.Text == null ? String.Empty : s.Text)

【讨论】:

  • (最终在 null 的情况下用 ?? 指定值)
  • 这会得到Severity的错误Error CS8072 An expression tree lambda may not contain a null propagating operator.
  • 是的,我想知道 Automapper 是否已更新为允许在 MapFrom 表达式中使用该运算符。合并运算符在 MapFrom 中不起作用,至少在旧版本的 Automapper 中是这样。
  • IIRC,您可以将合并运算符与 Automappers Resolve... 方法一起使用,但不能使用 Map... 方法。
  • @ca9163d9:奥奇,我明白了。显然MapFrom 有一个Expression&lt;something&gt; 参数。 Epression 树不能表达空条件;但是他们访问三元表达式。请查看我的更新答案。
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 2011-05-27
  • 2015-11-05
相关资源
最近更新 更多