动态创建 X 个类对象

Cod*_*ack 1 c# asp.net class dynamic

背景...

假设我有一个叫做汽车的类。我们只需要存储汽车名称和 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.
      }
Run Code Online (Sandbox Code Playgroud)

gjv*_*amp 5

这应该是诀窍:

int CarCount = 100;
Car[] Cars = Enumerable
            .Range(0, CarCount)
            .Select(i => new Car { Id = i, Name = "Chevy " + i })
            .ToArray();
Run Code Online (Sandbox Code Playgroud)

问候 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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意关键字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" };
}
Run Code Online (Sandbox Code Playgroud)

您可以将此代码文件添加到您的解决方案(右键单击项目...添加现有...)并编译它。现在您可以使用这些变量 car1 .. car100。