c# - 异步元组返回是否有等效的 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 #9开始,您 可以使用.struct
struct
MemberNotNullWhen
指定方法或属性在以指定的返回值条件返回时,将确保列出的字段和属性成员具有非空值。
注意:您将需要重新实现所有的 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
推荐阅读
- php - 升级到 Symfony flex (3.4) - 有很多捆绑包时的问题
- java - 如何导致矩阵形式的变化?
- php - 使用三元运算符简化条件表达式
- c++ - Pytorch 按元素应用各种功能(C++ API)
- node.js - 将带有 Content-Disposition 附件的 PNG 转换为 Nodejs 中的 Base64 或缓冲区
- django - DRF 中的观看次数增加
- netsuite - 如何在“新 nlobjSearchFilter”中添加 2 个条件?
- javascript - v-autocomplete 里面的值是字符串,但是在 v-model 里面是数字,怎么解决?
- php - 如何避免在 Laravel 中使用 AppServiceProvider 声明许多服务
- java - 如何使用普通变量传递系统变量以在命令行批处理脚本中调用java程序