首页 > 解决方案 > 异步元组返回是否有等效的 NotNullWhen C# 模式?

问题描述

在具有可空类型的 C# 中,可以实现一个智能的空检查“TryGet”,例如,

bool TryGetById(int id, [NotNullWhen(returnValue: true)] out MyThing? myThing)

这允许调用者跳过对 out var myThing 的空值检查。

不幸的是,异步不允许输出参数,并且使用元组返回的模式不允许这种智能的 NotNull 检查(至少,就我所发现的而言)。有替代方案吗?

有什么方法可以在异步元组返回类型上使用等效的“NotNullWhen”,例如,

Task<(bool Ok, [NotNullWhen(returnValue: true)] MyThing? MyThing)> TryGetById(int id)

标签: c#async-awaitnullable

解决方案


没有值元组的实现(还)。然而!从C #9开始 可以使用.struct structMemberNotNullWhen

MemberNotNullWhenAttribute 类

指定方法或属性在以指定的返回值条件返回时,将确保列出的字段和属性成员具有非空值。

注意:您将需要重新实现所有的 tupley 优点,如平等等。

世界上最人为的例子随之而来

#nullable enable

public readonly struct Test
{
   [MemberNotNullWhen(returnValue: true, member: nameof(Value))]
   public bool IsGood => Value != null;

   public string? Value { get; init; }
}

public static Task<Test> TryGetAsync()
   => Task.FromResult(new Test {Value = "bob"});

public static void TestMethod(string bob)
   => Console.WriteLine(bob);

用法

var result = await TryGetAsync();
if (result.IsGood)
   TestMethod(result.Value); // <= no warning

推荐阅读