稍后在程序中调整 C# 中的数组大小 [英] Resize array in C# later in the program

查看:32
本文介绍了稍后在程序中调整 C# 中的数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这在 C# 中是否可行但我在

I am not sure if this is possible in c# but i'm having a variable defined in

 public partial class Form1 : Form
 {...
   ...
    #region used variables
    public ulong[] logP = {0,0,0,0,0,0,0,0}
  ....
  ..

然后在程序中我想有一个选项来调整程序中的大小在主要例程将启动它并进行一些计算之前

Then later in the program i want have an option to adjust the size in the program before the main routines will launch over it and do some calculations

因为我喜欢用不同的数字和数组大小集进行测试,所以我想有一个选项来调整数组的大小,对于每个测试(但这个数组没有绑定到单个过程,它是一个全局变量,需要可调整大小.

Because i like to test with vaious sets of numbers and array sizes i would like to have an option to resize the array, for each test (but this array isnt bound to a single procedure, its a global variable that needs to be resizable.

由于整个程序的各个部分都在使用这个数组,(在各种功能下)我应该如何放置这个部分

As the whole program at various parts is using this array, (under various functions) how should i put this part

    ulong [] sumP = new ulong[numericupdown.valeu];

所以它会改变这个全局变量的大小?

So that it would change this global variable size ?

推荐答案

您不能调整数组大小;您必须声明一个所需大小的新数组,并将原始数组的内容复制到新数组中.

You cannot resize an array; you must declare a new array of the desired size and copy the contents of the original array into the new array.

更新:我不喜欢 Array.Resize - 它不会调整数组的大小(正如方法名称所暗示的那样),它会创建一个新数组并替换引用:

Update: I don't like Array.Resize - it doesn't resize the array (as the method name would suggest), it creates a new array and replaces the reference:

    static void Main(string[] args)
    {
        int[] a1 = new int[] { 1, 2, 3 };
        int[] a2 = a1;

        Console.WriteLine("A1 Length: {0}", a1.Length); // will be 3
        Console.WriteLine("A2 Length: {0}", a2.Length); // will be 3
        Array.Resize(ref a1, 10);
        Console.WriteLine("A1 Length: {0}", a1.Length); // will be 10
        Console.WriteLine("A2 Length: {0}", a2.Length); // will be 3 - not good

        Console.ReadLine();
    }

这篇关于稍后在程序中调整 C# 中的数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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