我写了一些代码,它有一个名为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>
问题是我不知道如何使用它们,请尽可能帮助我。
答案 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;
}
}
}
}