gpt4 book ai didi

c# - AutoMapping : Dereference of a possibly null reference? Null 条件运算符不适用于 AutoMapping

转载 作者:行者123 更新时间:2023-12-05 01:38:38 27 4
gpt4 key购买 nike

我正在为类 A 使用 AutoMapper和 B .该项目是一个 .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 上有以下警告:

Warning CS8602 Dereference of a possibly null reference.

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

我试图改变o.MapFrom(s => s.X.Value)o.MapFrom(s => s.X?.Value)使用 Null 条件。但它在 s.X?.Value 上出现了以下错误 .

Error CS8072 An expression tree lambda may not contain a null propagating operator

最佳答案

MapFrom接受 Expression<>而不是 Func<> ,您不能使用 Null 条件运算符。这不是 AutoMapper 的限制,而是 System.Linq.Expressions 中表达式树的限制。命名空间和 C# 编译器。

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

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

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

(根据@Attersson 的说法)如果要在 null 情况下分配不同的值,可以将空合并运算符与三元运算符结合使用:

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

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

关于c# - AutoMapping : Dereference of a possibly null reference? Null 条件运算符不适用于 AutoMapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490921/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com