简体   繁体   English

C#中的动态数组填充

[英]Dynamic Array Filling in C#

I'd like to share a very bizzare phenomenon I am currently working on.我想分享一个我目前正在研究的非常奇怪的现象。 Globally speaking, the task looks trivial as it is about filling some arrays.从全局来看,这个任务看起来微不足道,因为它是关于填充一些数组。 However after debugging several times my code, the error: Index was outside the bounds of the array does not look as trivial as it looks, and I wonder if I miss something.但是,在多次调试我的代码后,错误: Index was outside the bounds of the array看起来并不像看起来那么简单,我想知道我是否遗漏了什么。 I have hesitated before posting that thread to avoid any potential downvotes, but to be honest, this error is really weird to me, since all the defined variables retrieved from the debug mode matches my expectation.在发布该线程之前我犹豫了,以避免任何潜在的反对票,但老实说,这个错误对我来说真的很奇怪,因为从调试模式中检索到的所有定义的变量都符合我的期望。

As an illustration:举例说明:

int count = FileNameFromPath.Length;
int i = 0;
while (i < count)
{
    try
    {
        string[] outp = new string[]
        {
        "CS_" + FileNameFromPath[i]
        }

        ;
        DataTable SourceData = GetDataTabletFromCSVFile(FileDirectory[i]);
        string[] SavePath = new string[]
        {
        DirOutputOlis + @"\" + outp[i]
        }

        ;
        CreateCSVFileFromDataTable(SourceData, SavePath[i]);
        Console.WriteLine("File Processed in Output Directory: {0}", outp[i]);
        i++;
    }
    catch (InvalidOperationException exc)
    {
        using (StreamWriter writer = new StreamWriter(logPath, true))
        {
            writer.WriteLine("Message :" + exc.Message + "<br/>" + Environment.NewLine + "StackTrace :" + exc.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
        }

        Console.WriteLine("File not Processed to Directory:  {0}", FileNameFromPath);
        PrintException(exc);
        Console.WriteLine("--------------------------------------------------------------------------------\n");
        goto Exitx;
    }
}

I reiterate: outp , SourceData , SavePath , count=3 are all correct for i=0 , but the problem starts at the following increment i=1 in row SavePath even if for the latter case the former variables are correct too (from the debug mode).我重申: outpSourceDataSavePathcount=3对于i=0都是正确的,但问题开始于行SavePath中的以下增量i=1即使对于后一种情况,前一个变量也是正确的(来自调试模式)。

Looks like outp is defined as a 1-element array (so, only outp[0] is valid).看起来 outp 被定义为一个 1 元素数组(因此,只有 outp[0] 有效)。 If i > 0, you are accessing outside the array boundaries, hence the exception.如果 i > 0,则您正在访问数组边界之外,因此例外。 Same applies to SavePath.同样适用于 SavePath。

Since you want to have an array of elements, you can either既然你想要一个元素数组,你可以

  1. Declare outp/Savepath outside the while cycle, specifying the correct number of elements (once declared, arrays have fixed size)在 while 循环之外声明 outp/Savepath,指定正确的元素数量(一旦声明,数组具有固定大小)
  2. Declare them as a List rather than Array.将它们声明为列表而不是数组。 A List can be accessed via the [] operator, but also supports the .Add method allowing it to grow. List 可以通过 [] 操作符访问,但也支持 .Add 方法允许它增长。

You could go with something like你可以用类似的东西

List<string> outp = new List<string>();
List<string> SavePath = new List<string>();

for (int i = 0; i < FileNameFromPath.Length; ++i)
{
    outp.Add("CS_" + FileNameFromPath[i]);
    SavePath.Add(DirOutputOlis + @"\" + outp[i]);
}

Step through your code here and imagine what happens with different values of i :在这里逐步执行您的代码,想象一下不同的i值会发生什么:

// outp is an array with a *single* element
string[] outp = new string[]
{
    "CS_" + FileNameFromPath[i]
};
DataTable SourceData = GetDataTabletFromCSVFile(FileDirectory[i]);
// SavePath is an array with a *single* element
string[] SavePath = new string[]
{
    DirOutputOlis + @"\" + outp[i]
};
CreateCSVFileFromDataTable(SourceData, SavePath[i]);
Console.WriteLine("File Processed in Output Directory: {0}", outp[i]);
i++;

Since outp and SavePath only have 1 element, you will get an exception when you try to index them when i > 0 .由于outpSavePath只有 1 个元素,因此当您尝试在i > 0时对它们进行索引时会出现异常。 It's not clearly exactly what you were trying to do there.这不是很清楚你在那里试图做什么。 If you don't actually need an array, then just use a string.如果您实际上不需要数组,则只需使用字符串。 So it would become:所以它会变成:

string outp = "CS_" + FileNameFromPath[i];

and:和:

string SavePath = DirOutputOlis + @"\" + outp;

Or, if your intention was to store the values of outp and SavePath , then you need a collection defined outside of the while loop:或者,如果您打算存储outpSavePath的值,那么您需要在 while 循环之外定义一个集合:

string[] outp = new string[count];
string[] SavePath = new string[count];
// ...
while (i < count)
{
    outp[i] = "CS_" + FileNameFromPath[i];
    // ...
    SavePath[i] = DirOutputOlis + @"\" + outp[i];
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM