Passing array between forms and managing in arrays

后端 未结 4 1039
走了就别回头了
走了就别回头了 2020-12-20 03:46

I want to transfer an array from Form1 to Form2, then on Form2 add some values to the array. On Form1 button click I put this code:

        int[] arrayOfInt          


        
相关标签:
4条回答
  • 2020-12-20 04:20

    Rather use ArrayList or even better IList<T>. Arrays cannot be resized in C#

    0 讨论(0)
  • 2020-12-20 04:25

    Use List<Int> and use oList.Add(item) method to add elements as array is Fixed in Lenght (you already giving it size at a time of initialization) But if you want to use array at any cost then make a logic to create a new array upto the size of Old+ new added element and return that.

    UPDATED I believe you are facing problem because you have taken List of String instead or Int.

                List<int> oIntList = new List<int>();
                oIntList.Add(1);
                oIntList.Add(3);
                oIntList.Add(4);
                oIntList.Add(5);
    
                int[] oIntArr = oIntList.ToArray();
    
    0 讨论(0)
  • 2020-12-20 04:34

    You will have to use ref argument on frm2.TakeThis() method:

    Here is an MSDN article on it : Passing Arrays Using ref and out (C# Programming Guide).

    void TakeThis(ref Int32[] array)
    {
        // Change array
    }
    

    and use like:

    frm2.TakeThis(ref arrayOfInt);
    

    Arrays need to passed by reference if you want to persist changes to them.

    If you must not use an Array use a Collection like System.Collections.Generic.List<T>.

    0 讨论(0)
  • 2020-12-20 04:40

    Don't use arrays if you want a data structure that you need to add items to.

    Use a generic collection like List<T>.

    In your case, a list of integers would be a List<int>.

    IList<int> listOfInt = new List<int>();
    listOfInt.Add(19);
    listOfInt.Add(12);
    Form2 frm2 = new Form2();
    frm2.TakeThis(listOfInt);
    frm2.Show();
    

    When on Form2, your TakeThis function would look like this:

    public voidTakeThis(IList<int> listOfInt)
    {
      listOfInt.Add(34);
    }
    

    This will also work when passing the list to another form, as List is a reference type whereas arrays are value types. If you don't know what this means, see this article.

    0 讨论(0)
提交回复
热议问题