gpt4 book ai didi

c# - 索引超出范围异常与参数超出范围异常

转载 作者:太空狗 更新时间:2023-10-30 01:04:32 25 4
gpt4 key购买 nike

当使用列表对象时,检查超出范围的索引,例如

List<MyObject> allServices = new List<MyObject>();
var indexOf = 0;

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

在我认为它会抛出索引超出范围异常的地方,它会抛出参数超出范围异常。这是为什么,当它是我们正在测试的索引时?

如果它类似于 substring 方法,其中 substring(-1) 将作为参数,我会期待参数吗?

最佳答案

数组和列表都实现了IList<T>抛出 ArgumentOutOfRangeException而不是 IndexOutOfRangeException当您尝试访问负索引的项目时:

MSDN :

ArgumentOutOfRangeException: index is not a valid index in the 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

这就是它抛出 ArgumentOutOfRangeException 的原因的 IList<T>而不是 IndexOutOfRangeException数组。

关于c# - 索引超出范围异常与参数超出范围异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22856801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com