如何在C#中动态实例化一个类?

时间:2015-11-08 01:13:40

标签: c# class runtime instance instantiation

我需要创建一个未知数量的类实例,并能够在运行时跟踪它们。示例用户会说他们想要创建_n数量的汽车。然后应用程序实例化car01 - car_n,并且当应用程序运行时,用户可以使用汽车“X”并且实例将跟踪其自己的里程数。如何实例化汽车实例以及如何引用特定实例? 我知道我可以拥有这个级别和一些可笑的预定义汽车,但似乎如果用户想要创建5或6辆汽车,代码可能会弹出car1-car6。

class Program
{
    static void Main(string[] args)
    {
        Random rnd = new Random();
        Foo[] FooCar = new Foo[5];
        string[] _NamesForFoo = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf" };
        int FoosToMake = rnd.Next(1, _NamesForFoo.Length);
        for (int i = 0; i < FoosToMake; i++)
        {                
            FooCar[i] = new Foo(_NamesForFoo[i], rnd.Next(100,500));
            Console.WriteLine("You just created a FooCar named {0} with a count of {1}.", 
            FooCar[i]._FooName, FooCar[i]._FooCount);
        }
    }

    public class Foo
    {
        public string _FooName { set; get; }
        public int _FooCount { set; get; }

        public Foo(string _NameIn, int _CountIn)
        {
            _FooName = _NameIn;
            _FooCount = _CountIn;
        }
    }
}

响应中提供的链接不回答此示例的问题。集合或列表也不起作用。这是一个例子

class Program
{
    static void Main(string[] args)
    {
        Random rnd = new Random();
        string[] _NamesForFoo = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf" };
        int FoosToMake = rnd.Next(1, _NamesForFoo.Length);

        List<Foo> FooCar = new List<Foo>
        {
            for (int i = 0; i < FoosToMake; i++)
            {                
                new Foo(){_FooName = _NamesForFoo[i], _FooCount = rnd.Next(100,500)};
            }
        };
    }

    public class Foo
    {
        public string _FooName { get; set; }
        public int _FooCount { get; set; }

        public Foo(string _NameIn, int _CountIn)
        {
            _FooName = _NameIn;
            _FooCount = _CountIn;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用集合:

var cars = new List<Car>();

for (int i = 0; i < NumCarsNeeded; i++)
{
    cars.Add(new Car());
}

//Access car #1 (index 0)
cars[0].Mileage += 5;

答案 1 :(得分:0)

我不确定我是否完全理解它,但我认为这就是你要找的东西:

// To store common properties and methods, use an abstract class:
public abstract class Car {
  public string Make {get; set;};
  public string Model {get; set;};
// The rest of properties
}

// To store special data for a particular type of car:
public class Van: Car
{
   public string DoorType {get; set;}
   // the rest of properties
}

public class Truck: Car
{
//...
}

然后,为了实例化和维护汽车列表,使用多态:

List<Car> cars = new List<Car>();
Van v1 = new Van { Make="...", Model="...", DoorType="..." };
Truck t1 = new Truck { Make="...", Model="...", /*...*/ };

cars.Add(v1);
cars.Add(v2);

string doortype = (cars[0] as Van).DoorType;
string model = cars[0].Model;

我认为你有了这个主意。

答案 2 :(得分:0)

结果是一个类的数组是一个很好的方法。这是有效的例子。

class Program
{
    static void Main(string[] args)
    {
        Random rnd = new Random();
        Foo[] FooCar = new Foo[6];
        string[] _NamesForFoo = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf" };
        int FoosToMake = rnd.Next(1, _NamesForFoo.Length);

        Console.WriteLine("Making {0} FooCars.", FoosToMake);
        //create the cars
            for (int i = 0; i < FoosToMake; i++)               
            {                
                FooCar[i] = new Foo( _NamesForFoo[i], rnd.Next(100,500));
            }
        //list the cars
            for (int i = 0; i < FoosToMake; i++)
            {
                Console.WriteLine("FooCar {0} has a count of {1}", FooCar[i]._FooName, FooCar[i]._FooCount );
            }
        //modify a car
            FooCar[0]._FooCount += 2500;
        //show change to specific car
            Console.WriteLine("FooCar {0} now has a count of {1}", FooCar[0]._FooName, FooCar[0]._FooCount);

        Console.ReadKey();
    }

    public class Foo
    {
        public string _FooName { get; set; }
        public int _FooCount { get; set; }

        public Foo(string _NameIn, int _CountIn)
        {
            _FooName = _NameIn;
            _FooCount = _CountIn;
        }
    }
}