【问题标题】:IndexOutOfRange in Constructor C# [duplicate]构造函数 C# 中的 IndexOutOfRange [重复]
【发布时间】:2015-02-02 18:17:48
【问题描述】:

我有一个简单的类,像这样:

public class myClass
{
    public static readonly string[] stringArray= { "one", "two" };
    private string myString;

    public myClass (int _index)
    {
       if(_index > (stringArray.Length - 1) || _index < 0)
       {
           throw new IndexOutOfRangeException("Bad index.");
       }
       else
       {
           myString = stringArray[_index];
       }
    }

}

我正在运行简单的构造函数:myClass example = myClass(5);我有错误。 它不应该在不尝试创建新对象的情况下离开构造函数吗?

我不明白 throw 在那里是如何工作的。


编辑:对不起,我犯了一个错误。 if 部分应该有 stringArray.Length -1

【问题讨论】:

  • 这不是重复的。 OP 在他的代码中有一个类型,他需要帮助。
  • 你不明白为什么你的异常会被抛出,或者为什么在构造函数中抛出异常会导致对象无法初始化?
  • 我只想要这样的东西:myClass example = myClass(1); -> 没关系,我有我的对象 myClass example = myClass(5); -> 在控制台中写入错误。
  • 这里的问题是什么:为什么 myClass example = myClass(5);抛出异常?

标签: c#


【解决方案1】:

因为您将 5 作为 _index 传递给您的构造函数,所以以下 if 条件将为真

if(_index > (stringArray.Length - 1) || _index < 0)

因为数组的长度是 2 和 5 > 1。这会导致代码抛出 IndexOutOfRangeException,从而阻止构造函数返回对象的实例。此外,如果您在new myClass(5) 周围没有try-catch,则异常将冒泡并导致您正在运行的应用程序崩溃。

【讨论】:

    【解决方案2】:

    您的代码中有错字。您需要获取数组的长度而不是字符串。

    代码行应该:

     if(_index > (stringArray.Length - 1) || _index < 0)
    

    【讨论】:

      【解决方案3】:

      myString 为 null,因此当您访问 Length 属性时会收到 NullReferenceException。

      我的猜测是你想要的:

      if(_index > (stringArray.Length - 1) || _index < 0)
      

      【讨论】:

      • 我的猜测也是你的猜测。
      • 尽管如此它仍然不起作用,但我处理了那种异常。
      猜你喜欢
      • 1970-01-01
      • 2015-07-15
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 2014-12-17
      • 2014-08-21
      • 2023-04-03
      相关资源
      最近更新 更多