小编aes*_*aes的帖子

如何获取 C# null 状态以将 List<T?> 转换为 List<T>

我在 C# 可空上下文中使用可空引用类型。

我正在拿一个List<string>,然后将其转换为一个新的List<string?>,就像Select这样。null然后我用 a过滤掉s Where,但底层类型仍然是List<string?>

strings = strings
    .Select(s => method.ThatReturnsNullableString(s))
    .Where(s => s is not null)
    .ToList();
Run Code Online (Sandbox Code Playgroud)

当我尝试将其用作 时List<string>,我收到 CS8619 编译器警告。一个简单的解决方案是使用! null-forgiving 运算符并且警告消失,但我尝试尽可能少地使用它。

另一个解决方案是使用.Cast<string>,但我认为这会无缘无故地增加运行时开销。

我是否没有向编译器充分证明该集合的类型为string,或者我缺少什么?

.net c# linq nullable

3
推荐指数
1
解决办法
864
查看次数

标签 统计

.net ×1

c# ×1

linq ×1

nullable ×1