C#根据输入的字符串来创建类的实例

时间:2021-02-10 13:28:53   收藏:0   阅读:0
  abstract class Vehicle
    {
        public abstract void Drive();
    }
    
    class Car : Vehicle
    {
        public override void Drive()
        {
            Console.WriteLine("Car is driving...");
        }
    }

    class Bus : Vehicle
    {
        public override void Drive()
        {
            Console.WriteLine("Bus is driving...");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string typeName = Console.ReadLine();
            Type type = Type.GetType(new Program().GetType().Namespace + "." + typeName, true, true);
            Vehicle vehicle = (Vehicle)Activator.CreateInstance(type);
            vehicle.Drive();
            Console.ReadKey();
        }
    }

运行结果:
技术图片
技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!