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

  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();
        }
    }

运行结果:
C#根据输入的字符串来创建类的实例
C#根据输入的字符串来创建类的实例

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

上一篇:支付宝API


下一篇:.net5 core webapi项目实战之十七:F8用户上传自己的照片