C#8 可为空和不可为空的引用类型 - 仅当输入可为空时才为空输出

C#8 nullable and non-nullable reference types - nullable output only if input is nullable

我有一堆扩展方法可以将我的实体转换为 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)

您要的属性是NotNullIfNotNullAttribute

该属性接受您用来推断无效性的参数名称。

在你的情况下,这看起来像:

using System.Diagnostics.CodeAnalysis;

// ...

[return:NotNullIfNotNull("this")]
public static LocationDto? ToDto(this Location? @this)
{
    // Your code here
}