构造函数C#中的IndexOutOfRange

时间:2014-12-04 18:29:14

标签: c#

我有简单的课程,类似这样:

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);而且我有错误。 它不应该在不尝试创建新对象的情况下离开构造函数吗?

我不明白投掷是如何运作的。


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

3 个答案:

答案 0 :(得分:3)

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

我的猜测是你想要的:

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

答案 1 :(得分:1)

因为您将_index作为if(_index > (stringArray.Length - 1) || _index < 0) 传递给构造函数,所以以下if条件为真

IndexOutOfRangeException

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

答案 2 :(得分:0)

您的代码中有拼写错误。你需要得到数组的长度而不是字符串。

代码行应该:

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