为什么我的结构数组没有使用 Array.Resize 调整大小

本文关键字:Resize Array 调整 结构 我的 数组 为什么 | 更新日期: 2023-09-27 17:55:57

我有一个结构数组声明为

public struct classMates
    {
        public string first;
        public string last;
        public string ID;
    }

我正在使用 StreamReader 读取.txt文件,我的变量对应于它们的相关值。 即 第一个 == 名字,ID == 电话号码。

我的结构数组被设计为:

classMates[] classMateInfo = new classMates[43];

我有一个方法,应该向我的.txt文件添加一个新成员并将其附加到我声明的数组的末尾。但是,为了做到这一点,我需要调整数组 + 1 的大小才能获得新成员。否则,它只会覆盖现有成员。

在调用我的方法添加新成员后,我就有了Array.Resize。但是,一旦我完成了该方法,StreamWriting 就会产生并将其保存到准备写入文件的变量中。

static void addClassMates(classMates[] classMateInfo)
    {
        //I DECLARE MY ARRAY RESIZE HERE
        Array.Resize(ref classMateInfo, classMateInfo.Length + 1);
        //I am essentially creating a new space in my array for a new member, below.
        Console.Write("Enter first name: ");
        classMateInfo[classMateInfo.Length - 1].first = Console.ReadLine();
        Console.Write("Enter last name: ");
        classMateInfo[classMateInfo.Length - 1].last = Console.ReadLine();
        Console.Write("Enter phone number: ");
        classMateInfo[classMateInfo.Length - 1].ID = Console.ReadLine();
        Console.WriteLine("Would you like to save the changes back to the file? [Y/N]");
        string temp = Console.ReadLine();
        if ((temp == "Y") || (temp == "y"))
        {                
            editNumber(classMateInfo);//A method where it saves it to variables ready to be StreamWritten.
        }
    }

之后,它然后移动到一个方法上,将其添加到文件中。但是,通过轻微调试,我发现我的数组中没有为我尝试输入的这个值添加新的空间。我有 [42] 个数组占位符,在 Array.Resize 的帮助下,这应该是实际的 [43]。

我的

问题是,为什么我的数组没有按照我的要求调整大小?看来我放错了地方,我真的不清楚我应该把它放在哪里。

为什么我的结构数组没有使用 Array.Resize 调整大小

您需要通过以下方式声明您的方法:

static void addClassMates(ref classMates[] classMateInfo)

请注意参数的ref