-1

Cars私はそれが以下のような名前のクラスを持っているいくつかのコードを書きました:

public class Cars
{
    public Cars()
    {
        string ma;
        int pe;
        Console.WriteLine("PLz put the car  name:");
        ma = Console.ReadLine();
        Console.WriteLine("PLz put  car no  :");
        pe = Convert.ToInt16( Console.ReadLine());
    }

}

次に、リストや配列など、複数のオブジェクトを作成します。
私はこのコードを知っていますが、複数の車を自動的に作成できる場合に備えて、forループを使用する方法がわかりません

Cars[] car = new Cars[10];

また

List <Cars> 

使い方がわからないので、よろしければ手伝ってください。

4

2 に答える 2

1

あなたが探しているのはこれだと思います:

Cars[] car = new Cars[10];

for (int i = 0; i < 10; i++)
{
    car[i] = new Cars();
}

またはを使用してList<T>

List<Cars> car = new List<Cars>();

for (int i = 0; i < 10; i++)
{
    car.Add(new Car());
}    

ただし、Console関数をクラスの外に移動し、代わりに次のようなコンストラクターを使用することをお勧めします。

public Cars(string ma, int pe)
{
    // assign to properties, etc.
}
于 2012-11-23T19:30:56.447 に答える
0

以下のようなものが役に立ちます。しかし、みんなが言ったように、基本から始める必要があります。本から読むのが常に最善です.

namespace Cars
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Cars> carList = new List<Cars>();

            Console.WriteLine("PLz put the car  name:");
            string ma = Console.ReadLine();
            Console.WriteLine("PLz put  car no  :");
             int pe = Convert.ToInt16(Console.ReadLine());

            carList.Add(new Cars(ma,pe));
        }



        public class Cars
        {

            string ma;
            int pe;

            public Cars(string carName, int reg)
            {
                ma = carName;
                pe = reg;

            }

        }
    }
}
于 2012-11-23T19:46:40.670 に答える