动态创建X个类对象
本文关键字:对象 创建 动态 | 更新日期: 2023-09-27 18:22:51
背景。。。
比方说我有一门课叫汽车。我们只需要存储汽车名称和ID。还可以说,我有一个基于管理类的管理页面,我在一个名为totalCars 的int中设置了要创建的汽车总数
问题是:如何动态地将汽车创建为可以从代码中任何地方访问的字段,同时根据totalCars中的数字创建汽车总数?
示例代码:
Cars car1 = new Cars();
int totalCars;
//Somehow I want to create cars objects/fields based on the
//number in the totalCars int
protected void Page_Load(object sender, EventArgs e)
{
car1.Name = "Chevy";
car1.ID = 1;
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = car1.Name.ToString();
//this is just a sample action.
}
这应该是一个技巧:
int CarCount = 100;
Car[] Cars = Enumerable
.Range(0, CarCount)
.Select(i => new Car { Id = i, Name = "Chevy " + i })
.ToArray();
问候GJ
编辑
如果你只是想知道你会如何做这样的事情(你不应该做),试试这个:
using System.IO;
namespace ConsoleApplication3 {
partial class Program {
static void Main(string[] args) {
Generate();
}
static void Generate() {
StreamWriter sw = new StreamWriter(@"Program_Generated.cs");
sw.WriteLine("using ConsoleApplication3;");
sw.WriteLine("partial class Program {");
string template = "'tCar car# = new Car() { Id = #, Name = '"Car #'" };";
for (int i = 1; i <= 100; i++) {
sw.WriteLine(template.Replace("#", i.ToString()));
}
sw.WriteLine("}");
sw.Flush();
sw.Close();
}
}
class Car {
public int Id { get; set; }
public string Name { get; set; }
}
}
注意关键字partial class
,这意味着您可以拥有一个跨越多个源文件的类。现在,您可以手动编写一个代码,然后生成另一个。
如果您运行此代码,它将生成以下代码:
using ConsoleApplication3;
partial class Program {
Car car1 = new Car() { Id = 1, Name = "Car 1" };
Car car2 = new Car() { Id = 2, Name = "Car 2" };
...
Car car99 = new Car() { Id = 99, Name = "Car 99" };
Car car100 = new Car() { Id = 100, Name = "Car 100" };
}
您可以将此代码文件添加到您的解决方案中(右键单击project..添加现有..)并对其进行编译。现在您可以使用这些变量car1。。car100.
使用List<Cars>
:
List<Cars> cars = new List<Cars>();
int totalCars;
protected void Page_Load(object sender, EventArgs e)
{
cars = new List<Cars>();
for(int i=0; i<totalCars; i++)
{
cars.Add(
new Cars()
{
Name = "Car #" + i;
ID = i;
}
);
}
}