【问题标题】:C#8 nullable and non-nullable reference types - nullable output only if input is nullableC#8 可空和不可空引用类型 - 仅当输入可空时才可空输出
【发布时间】: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


【解决方案1】:

您要求的属性是NotNullIfNotNullAttribute

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

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

using System.Diagnostics.CodeAnalysis;

// ...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 2018-07-18
    • 2020-04-19
    • 2010-10-21
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多