错误:索引超出了 c# 中数组的边界
本文关键字:数组 边界 索引 错误 | 更新日期: 2023-09-27 18:32:00
我正在尝试使用c#接口概念为圆形和方形区域编写小程序。在给出特定条件if (args[0] == "S")
时,IndexOutOfRangeException
出现错误:
if (args[0]=="S")
fig = new Square();
if (args[0]=="C")
fig = new Circle();
如果args
为空,就会发生这种情况。您不能请求空数组的第一个元素,因为没有一个元素。您应该先检查长度:
if (args.Length == 0)
{
// Maybe exit? Is it valid not to specify any arguments?
}
// Either use an "else" here, or if you've quit in the "if" block
// then you don't need to because you know that there's at least
// one argument by now