在C#中创建一个类型的多个对象

时间:2012-11-23 19:27:23

标签: c# arrays object

我写了一些代码,它有一个名为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> 

问题是我不知道如何使用它们,请尽可能帮助我。

2 个答案:

答案 0 :(得分: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.
}

答案 1 :(得分: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;

            }

        }
    }
}