【问题标题】:Error : Index was outside the bounds of the array in c# [duplicate]错误:索引超出了c#中的数组范围[重复]
【发布时间】:2016-01-27 07:21:38
【问题描述】:

我正在尝试使用 c# 接口概念为圆形和正方形区域编写小程序。在给出特定条件if (args[0] == "S") 时出现错误IndexOutOfRangeException

if (args[0]=="S")
    fig = new Square();
if (args[0]=="C")
    fig = new Circle();

【问题讨论】:

  • 您没有检查 args 数组是否具有非零长度。最好将代码作为文本包含在此处而不是链接到图像。

标签: c# indexing was


【解决方案1】:

如果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

【讨论】:

    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多