索引超出范围异常 vs 参数超出范围异常

6
当使用列表对象时,如果检查的索引超出范围,例如:
List<MyObject> allServices = new List<MyObject>();
var indexOf = 0;

lnkBack.NavigateUrl = allServices[indexOf - 1].FullURL;

当我认为它会抛出一个索引超出范围异常时,它却抛出了一个参数超出范围的异常。为什么呢?毕竟我们正在测试一个索引。

如果是像子字符串方法,那么substring(-1)就会是一个参数,这时我才会期望抛出参数异常。

2个回答

6

数组和列表都实现了 IList<T> 接口,当你尝试访问一个负索引的项时,会抛出一个 ArgumentOutOfRangeException 而不是 IndexOutOfRangeException:

MSDN:

ArgumentOutOfRangeException: 索引不是 IList<T> 中的有效索引

你可以通过以下代码重现这个问题:

IList<string> test = new string[]{ "0" };
string foo = test[-1];  // ArgumentOutOfRangeException

如果你将其用作string[],那么你会得到期望的IndexOutOfRangeException

string[] test = new string[]{ "0" };
string foo = test[-1];  // IndexOutOfRangeException

这就是为什么它会抛出 IList<T>ArgumentOutOfRangeException 而不是数组的 IndexOutOfRangeException

我认为最后一句话是相反的。IList<T>.this[int] 抛出 ArgumentOutOfRangeException,而数组抛出 IndexOutOfRangeException - David Lechner
@DavidLechner:谢谢,已经修正了,迟来总比不来好 ;) - Tim Schmelter

3
作为一个数组访问列表只是一种语法特征。背后发生的事情是代码使用 Item property,将索引作为参数发送。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接