我有一门简单的课,就像这样:
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样例= myClass(5);而且我有错误。它不应该离开构造函数而不尝试创建新对象吗?
我不明白扔球是怎么回事。
编辑:对不起,我犯了一个错误。if部分应该有stringArray.Length -1 .
发布于 2014-12-04 18:42:00
因为要将5作为_index传递给构造函数,所以如果条件为真,则如下所示
if(_index > (stringArray.Length - 1) || _index < 0)因为数组的长度是2和5> 1,这会导致代码抛出IndexOutOfRangeException,从而阻止构造函数返回对象的实例。此外,如果您在try-catch周围没有一个new myClass(5),那么异常就会出现,并导致运行中的应用程序崩溃。
发布于 2014-12-04 18:31:26
myString是空的,所以当您访问Length属性时,您将得到一个Length。
我猜你想:
if(_index > (stringArray.Length - 1) || _index < 0)发布于 2014-12-04 18:32:44
你的代码中有错误。您需要得到数组的长度,而不是字符串。
代码行应:
if(_index > (stringArray.Length - 1) || _index < 0)https://stackoverflow.com/questions/27301306
复制相似问题