【发布时间】:2020-02-10 20:14:02
【问题描述】:
我有这样的代码:
IEnumerable<string?> items = new [] { "test", null, "this" };
var nonNullItems = items.Where(item => item != null); //inferred as IEnumerable<string?>
var lengths = nonNullItems.Select(item => item.Length); //nullability warning here
Console.WriteLine(lengths.Max());
如何以方便的方式编写此代码:
- 没有可空性警告,因为
nonNullItems类型被推断为IEnumerable<string>。 - 我不需要添加未经检查的不可为空性断言,例如
item!(因为我想从编译器的健全性检查中受益,而不是依赖于我是一个无错误的编码器) - 我不添加运行时检查的不可为空性断言(因为这在代码大小和运行时都是无意义的开销,并且在人为错误失败的情况下比理想情况晚)。
- 解决方案或编码模式可以更广泛地应用于可为空引用类型的其他项目序列。
我知道这个解决方案,它利用了 C# 8.0 编译器中的流敏感类型,但它......不是很漂亮,主要是因为它很长而且很吵:
var notNullItems = items.SelectMany(item =>
item != null ? new[] { item } : Array.Empty<string>())
);
有更好的选择吗?
【问题讨论】:
标签: c# nullable nullable-reference-types