【问题标题】:Why is my array of struct not resizing with Array.Resize?为什么我的结构数组没有使用 Array.Resize 调整大小?
【发布时间】:2015-08-28 18:52:42
【问题描述】:

我有一个结构数组声明为

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

我正在使用 StreamReader 读取 .txt 文件,并且我的变量对应于它们的相关值。 IE。 first == 名字,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]。

我的问题是,为什么我的数组没有按照我的要求调整大小?好像放错地方了,实在不知道该放哪里。

【问题讨论】:

  • 检查方法 addClassMates 中的数组大小,看起来您正在比较调用方法后的数组大小。您不能在方法中修改数组的引用。
  • struct 并不像您认为的那样。你为什么不使用List<T>

标签: c# arrays struct resize streamwriter


【解决方案1】:

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

static void addClassMates(ref classMates[] classMateInfo)

注意参数的ref

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2014-12-28
    • 1970-01-01
    • 2017-01-11
    • 2017-01-01
    • 2021-03-22
    相关资源
    最近更新 更多