作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
!String.IsNullOrEmpty(x-6ren">
使用 .NET 6 我有以下内容:
List<String> values = new List<String?> { null, "", "value" }
.Where(x => !String.IsNullOrEmpty(x))
.Select(y => y)
.ToList();
但我收到警告:
Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'.
我认为使用
.Where(x => !String.IsNullOrEmpty(x))
会解决问题,但事实并非如此。如何解决这个问题?
最佳答案
这是您了解得更多的一种情况,可以向编译器保证该值不是 null
通过.Select(y => y!)
List<string> values = new List<string?> { null, "", "value" }
.Where(x => !string.IsNullOrEmpty(x))
.Select(y => y!)
.ToList();
注意 : .Select(y => y.Value)
不会起作用,因为字符串是引用类型 和string?
代表一个可空引用类型,而不是一个可空值类型
如 @Patrick Artner 的评论中所述.您也可以使用 .Cast<string>()
达到类似的效果,本质上只是通用方法中的迭代器和常规转换,从而确保您获得所需的结果。
List<string> values = new List<string?> { null, "", "value" }
.Where(x => !string.IsNullOrEmpty(x))
.Cast<string>()
.ToList();
还有另一种方式(尽管推理起来有点困难)但可能更有效
List<string> values = new List<string?> { null, "", "value" }
.Where(x => !string.IsNullOrEmpty(x))!
.ToList<string>();
关于c# - 如何在 .NET 6/C# 10 中将 List<String?> 转换为 List<String>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70238748/
我是一名优秀的程序员,十分优秀!