我有一个“exampleClass”,它有一个集合“exampleCollection”。如果 exampleClass.ExampleCollection.Count = 0,exampleClass.ExampleCollection.Select(.... 那么该查询会产生错误吗?
我正在使用 c#,使用 linq 谢谢!
我有一个“exampleClass”,它有一个集合“exampleCollection”。如果 exampleClass.ExampleCollection.Count = 0,exampleClass.ExampleCollection.Select(.... 那么该查询会产生错误吗?
我正在使用 c#,使用 linq 谢谢!
不,您只会收到一个空的IEnumerable<T>,更具体地说是一个WhereSelectListIterator<T, bool>.
但有趣的是,如果集合为 null,则会在扩展方法 Select内部抛出错误。行为是不同的,因为 Select 方法不是您的集合的实例方法,它是一个扩展方法,如下所示:
IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
使用扩展方法,您的对象作为参数传递给静态方法(扩展),因此 NullRererenceException 可能会或可能不会在其中抛出(取决于内部实现)。在 Select 方法的情况下,
如果
exampleClass.ExampleCollection.Count() == 0,会exampleClass.ExampleCollection.Select(....)产生错误吗?
不,它只会产生一个空的IEnumerable<T>. First()并且Last()会产生错误但不会Select()。
如果exampleClass.ExampleCollection是,null那么您将获得一个NullReferenceException.