0

このプログラムは、説明のみを目的としています。入力として整数を取り、それがゼロより大きい場合は、ArrayList にその整数を使用して ArrayList を作成します。私はこの多くの (間違った) 方法を試しましたが、最終的に以下に示すものに落ち着きました。ただし、見た目はあまり好きではありません。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter in a number of the size of the ArrayList that you want: ");
            int arraySize = int.Parse(Console.ReadLine());
            if (arraySize > 0)
            {
                ArrayList newList = CreateList(arraySize,out newList);
                newList.Add(arraySize);
                Console.WriteLine("the size of the array is {0}",newList.Count);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("You did not create an ArrayList");
            }
            Console.WriteLine("here you can't access the array");
            Console.ReadLine();




        }
        public static ArrayList CreateList(int x,out ArrayList outList)
        {
            ArrayList al = new ArrayList(x);
            outList= al;
            return outList;

        }
    }

私の思考プロセスは、ユーザーが特定のアクションを決定した場合、プログラムはリソースを節約するために ArrayList を作成しないというものでした (例を考えるとばかげた例、私は知っています) 。ただし、メイン メソッドで ArrayList を初期化する必要があります。行を取り出すとnewList.Add(arraySize)、ユーザーが 0 より大きい数値を入力すると、プログラムは出力 0 で実行されます。 0 より大きい場合、要素を追加する準備ができている ArrayList になりますか? したがって、行をコメントアウトしてもnewList.Add(arraySize)、プログラムは ArrayList のサイズを 1 として出力します (数値が 0 より大きい場合)。

この例では、要素の数は最大 1 であり、ユーザーが入力できる数ではありません。

4

4 に答える 4

1

ArrayList コンストラクターの Int パラメーターは「初期容量」であり、これはパフォーマンス機能 (最大容量に達するまでアイテムが追加されている間、リストのサイズは変更されません) であるため、リストの実際のサイズとは違いはありません。1 つのアイテムを含むリストを返したい場合は、そのアイテムをCreateList関数内に追加します。

于 2013-04-17T22:49:56.017 に答える