【发布时间】:2020-11-17 18:21:36
【问题描述】:
我有一堆扩展方法可以将我的实体转换为DTOs,如下所示。
public static LocationDto? ToDto(this Location? @this)
{
if (@this == null) return null;
return new LocationDto
{
Id = @this.Id,
Text = @this.Name,
ParentId = @this?.Parent?.Id,
};
}
这里的问题是,如果你传递不可为空的实体仍然会收到一个可空的并且你不能定义一个public static LocationDto ToDto(this Location @this),因为它们会被编译成相同的方法。
另外,我不喜欢在我打电话的时候使用!。所以以下不是我的答案。
Location entity = AMethod();
LocationDto dto = entity.ToDto()!;
是否有属性或语法可以告诉编译器此方法的行为方式?有点像:
public static [NullableOnlyIfInputIsNull] LocationDto? ToDto(this Location? @this)
【问题讨论】:
-
c#-9.0 具有可为空的引用类型。
-
@rafaelgonzalez 是的,你是对的。 C# 从 C#8 开始就有。
标签: c# c#-8.0 nullable-reference-types