简体   繁体   English

Java的NoSuchElementException是否具有C#等效项?

[英]Is there a C# equivalent for Java's NoSuchElementException?

Java的NoSuchElementException是否具有C#等效项?

.NET usually uses InvalidOperationException for that. .NET通常为此使用InvalidOperationException You should not catch NoSuchElementException anyway because it usually indicates a program bug. 无论如何,您都不应捕获NoSuchElementException ,因为它通常表示程序错误。 For that reason the concrete exception type does not matter that much in this use case. 因此,在此用例中,具体的异常类型无关紧要。

Unfortunately, InvalidOperationException is used in many places for many different things. 不幸的是, InvalidOperationException在许多地方用于许多不同的事情。 You often can't tell much from it. 您常常不能从中看出很多。 This is a flaw in the BCL's exception hierarchy. 这是BCL异常层次结构中的一个缺陷。

In Java, NoSuchElementException is used to indicate that the end of an enumeration has been reached: 在Java中, NoSuchElementException用于指示已达到枚举的末尾:

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration. EnumerationnextElement方法抛出,以指示该Enumeration中没有更多元素。

The .NET Framework uses a different interface, where IEnumerator.MoveNext would return false , rather than throwing an exception, when the end of an enumeration is reached: .NET Framework使用另一个接口,当到达枚举结束时, IEnumerator.MoveNext将返回false ,而不是引发异常:

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false . 如果MoveNext通过集合的末尾,则枚举数将位于集合中最后一个元素之后,并且MoveNext返回false When the enumerator is at this position, subsequent calls to MoveNext also return false . 当枚举数位于此位置时,对MoveNext后续调用也将返回false

Edit : Rawling correctly points out that issues might still arise if the Current property is accessed beyond the end of the collection. 编辑 :Rawling正确指出,如果超出集合末尾访问Current属性,仍然可能会出现问题。 In such cases, the behaviour is not consistent. 在这种情况下,行为不一致。 IEnumerator.Current states that an exception will be thrown; IEnumerator.Current声明将抛出异常; however, List<T>.Enumerator.Current states that the behaviour is undefined: 但是, List<T>.Enumerator.Current指出该行为是未定义的:

For better performance, this property does not throw an exception if the enumerator is positioned before the first element or after the last element. 为了获得更好的性能,如果枚举数位于第一个元素之前或最后一个元素之后,则此属性不会引发异常。 The value of the property is undefined. 该属性的值是不确定的。

Edit 2 : It appears that there isn't an equivalent exception. 编辑2 :似乎没有等效的例外。 In .NET, you must not ignore the state of the enumerator (as identified, for example, through the return value of the MoveNext method), or you will run into undefined behaviour which could unpredictably break your application. 在.NET中, 您一定不能忽略枚举器的状态 (例如,通过MoveNext方法的返回值来标识),否则您将遇到未定义的行为,这可能会意外中断应用程序。

Linq uses: Linq使用:

[InvalidOperationException]

With the message: 随着消息:

Sequence contains no elements 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM