Skip to main content
 首页 » 编程设计

c#之LINQ Enumerable.All 如果集合为空则始终返回 True

2024年02月04日42xiaohuochai

<分区>

    class Program 
    { 
        static void Main() 
        { 
            var list = new List<Foo>(); 
            var a = list.All(l => l.BoolBar == true);//true 
            var s = list.All(l => l.Bar.Contains("magicstring"));//true 
        } 
    } 
    public class Foo 
    { 
        public bool BoolBar{ get; set; } 
        public string Bar{ get; set; } 
    } 

基于这个片段,我想知道为什么 Linq 框架的创建者选择为空集合使用这个解决方案?另外,由于 Visual Studio 和 Linq 都是 MS 产品,如果用户在执行 .All 之前没有检查集合是否为空,为什么智能感知不会发出警告?我认为它会导致很多意想不到的结果。