指数数组的边界之外。 C# [英] Index was outside the bounds of the array. C#

查看:96
本文介绍了指数数组的边界之外。 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我是新用户。我有一个问题,请有人帮我吗?

hi guys i'm new user. i have a problem in this error please anyone can help me?

    protected void Button1_Click(object sender, EventArgs e)
    {

        String[] SinhalaWords = new String[70130];
        int count = 0;
        String Word;
        String path = Server.MapPath("~\\Resarch\\new.txt");
        StreamReader sre = new StreamReader(path);

        while ((Word = sre.ReadLine()) != null)
        {
            SinhalaWords[count] = (Word.ToString().Trim());        
         
           TextBox1.Text = SinhalaWords[count];//this line show Index was outside the bounds of the array. error
           count++;
        }
   
       
     
    

    }
}





我尝试了什么:



索引超出了数组的范围。 c#我想读取此文本文件并将所有文本文件内容存储到数组中。最后我希望在文本框中显示所有数组元素值



What I have tried:

index was outside the bounds of the array. c# i want to read this text file and store all text file content in to the array. finally i want display all the array element values in the text box

推荐答案

在代码中停止使用魔术数字,如70130 - 他们很难让维护,并且容易出现这样的问题。

在这种情况下,您的代码非常糟糕 - 您将文本框设置为文件的每一行,并始终覆盖最后一行。

您的代码很容易被替换为:

Stop using "magic numbers" like "70130" in your code - they make it very hard to maintain, and are prone to problems like this.
And in this case, your code is pretty bad - you set the textbox to every single line of the file, and always overwrite the last one.
Your code could easily be replaced with:
string[] SinhalaWords = File.ReadAllLines(Server.MapPath("~\\Resarch\\new.txt"));
TextBox1.Text = SinhalaWords[SinhalaWords.Length - 1];

哪个不会有问题,而且工作速度会快很多!

Which wouldn't have the problem and would work a whole lot faster!


Quote:

索引超出了数组的范围。

Index was outside the bounds of the array.

它只是意味着你的文本文件有超过70130个单词。

要么你知道单词的数量相应地调整数组的大小,或者你用类似的东西调整大小。

It simply mean that your text file have more than 70130 words.
Either you know the number of words and size the array accordingly, or you resize on fly with something like.

SinhalaWords.add(Word.ToString().Trim());



将值添加到C#数组 - 堆栈溢出 [ ^ ]


当您尝试从阵列中不存在的数组中获取特定Index的任何ITEM时发生此异常。

所以在你的情况下,你的数组长度为'70130'b如果您的文本文件内容超过指定长度,您的应用程序可能会抛出异常

我认为您需要删除'70130'号码的HARDCODED逻辑并添加一些不同的

什么你想做什么?你想要哪个输出?
This exception occurred when you are trying to get any ITEM from specific Index from an array which is not present in array.
so in your case, your array length is '70130' but if your textfile contents are more than specified length your application may throw an exception
I think you need to remove HARDCODED logic of '70130' number and put some different
What you want to do exactly ? which output you want ?


这篇关于指数数组的边界之外。 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆