背景...
假设我有一个名为汽车的类(class)。我们只是要存储汽车名称和 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" };
}
您可以将此代码文件添加到您的解决方案中(右键单击项目.. 添加现有的..)并编译它。现在您可以使用这些变量 car1 .. car100。
关于c# - 动态创建 X 个类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9162321/