首页 > 图灵资讯 > 技术篇>正文

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

2023-06-06 09:28:13

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#根据输入的字符串来创建类的实例_ide

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

上一篇 .net 中的async,await理解
下一篇 #yyds干货盘点# LeetCode程序员面试金典:打家劫舍

文章素材均来源于网络,如有侵权,请联系管理员删除。