Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#无法解释的索引自动异常_C#_Indexoutofrangeexception - Fatal编程技术网

C#无法解释的索引自动异常

C#无法解释的索引自动异常,c#,indexoutofrangeexception,C#,Indexoutofrangeexception,我得到一个奇怪的索引超出范围异常 以下是我的代码片段: string[] st2 = **An Array of up to 10**; // If not enough in st2, add from st if (st2.Length < 10) { string[] st = **An Array of up to 10**; try { int index = 0; for (int i = st2.Length - 1;

我得到一个奇怪的索引超出范围异常

以下是我的代码片段:

string[] st2 = **An Array of up to 10**;

// If not enough in st2, add from st
if (st2.Length < 10)
{
    string[] st = **An Array of up to 10**;
    try
    {
        int index = 0;
        for (int i = st2.Length - 1; i < 10; i++)
        {
            st2[i] = st[index];
            index = index + 1;
        }%%%
    }
    catch (IndexOutOfRangeException)
    {

    }
}
string[]st2=**最多为10**的数组;
//如果st2中的数据不足,请从st中添加
如果(st2.2长度<10)
{
字符串[]st=**一个最多为10**的数组;
尝试
{
int指数=0;
for(inti=st2.Length-1;i<10;i++)
{
st2[i]=st[index];
指数=指数+1;
}%%%
}
捕获(IndexOutOfRangeException)
{
}
}
我放置了try-and-catch以查看是否可以简单地忽略异常,但是这不起作用


异常在%%%处引发。有什么想法吗?我进行调试只是为了确保它不是这两个数组中的任何一个,在这两种情况下,我和索引都是可以接受的。(即使st的长度已确认为10,仍在索引=1处抛出)

变量st只有1项,请参见以下行:st3[i]=st[index];。I从0变为9,当I=1时发生异常。

您的数组给出了此异常。因为它的尺寸小于10。您需要将
st2
st
复制到大小为10的新阵列。稍后将其分配给
st2

string[] st2 = **An Array of up to 10**;

// If not enough in st2, add from st
if (st2.Length < 10)
{
    string[] st = **An Array of up to 10**;
    try
     {
        string[] st3 = new string[10];
        Array.Copy(st2, st3, st2.Length); 
        int index = 0;
        for (int i = st2.Length; i < 10; i++)
        {
            st3[i] = st[index];
            index = index + 1;
        }
        st2 = st3;
     }
     catch (IndexOutOfRangeException)
     {

     }
    }
string[]st2=**最多为10**的数组;
//如果st2中的数据不足,请从st中添加
如果(st2.2长度<10)
{
字符串[]st=**一个最多为10**的数组;
尝试
{
字符串[]st3=新字符串[10];
数组.Copy(st2,st3,st2.Length);
int指数=0;
for(int i=st2.Length;i<10;i++)
{
st3[i]=st[index];
指数=指数+1;
}
st2=st3;
}
捕获(IndexOutOfRangeException)
{
}
}

是否尝试清理解决方案并重新启动visual studio?`为什么不
for(int i=0;i
?您的逻辑没有任何意义。循环将在其aexond迭代中访问
st2[st2.length]
,这已经超出了结束时间。您不能通过分配未使用的索引来扩大.net数组。根据您的问题,您可以有不同长度的数组,但可以将它们视为相同长度的数组。你到底想做什么?
Array.Copy(st2,st,st2.Length)
将为youHiya解决此问题,虽然这很可能回答问题,但请注意,其他用户可能没有您那么了解。你为什么不补充一点解释,为什么这实际上是一个问题?谢谢