[英]creating multiple objects of a type in C#
我编写了一些代码,其中有一个名为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>
问题是我不知道如何使用它们,如果可以的话请帮助我。
我认为您正在寻找的是:
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.
}
如下所示的内容将对您有所帮助。 但是就像你们所说的那样,您需要从基础开始,从书本上阅读总是最好的。
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;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.