动态创建X个类对象

时间:2012-02-06 15:17:55

标签: 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.
      }

2 个答案:

答案 0 :(得分:4)

这应该是诀窍:

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。

答案 1 :(得分:2)

使用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;
                }
              );
      }          
  }