如何通过运行时字符串输入实例化类?附C#代码示例
使用Activator.CreateInstance根据字符串创建类实例
首先,你需要先定义宠物基类,让所有宠物类继承它,这样创建实例后可以统一操作(比如设置名字、调用通用方法):
// 宠物基类 public abstract class Pet { public string Name { get; set; } public abstract void MakeSound(); } // 具体宠物类 public class Dog : Pet { public override void MakeSound() { Console.WriteLine($"{Name} 汪汪叫!"); } } public class Cat : Pet { public override void MakeSound() { Console.WriteLine($"{Name} 喵喵叫!"); } } public class Hamster : Pet { public override void MakeSound() { Console.WriteLine($"{Name} 吱吱叫!"); } } public class Gerbil : Pet { public override void MakeSound() { Console.WriteLine($"{Name} 叽叽叫!"); } }
接下来修改你的Program类,用Activator.CreateInstance替代硬编码的if分支:
class Program { static void Main() { Program petManager = new Program(); string petName = petManager.GetName(); petManager.CreatePetInstance(petName); } public void CreatePetInstance(string petName) { Console.WriteLine($"What species is {petName}? We currently have: Dog/Cat/Hamster/Gerbil"); string answer = Console.ReadLine()?.Trim().ToLower() ?? string.Empty; // 将用户输入的小写字符串转为类名格式(首字母大写) string className = char.ToUpper(answer[0]) + answer.Substring(1); // 获取对应类型(类在自定义命名空间下时,要加上命名空间前缀,比如"MyNamespace.Dog") Type petType = Type.GetType(className); if (petType == null || !typeof(Pet).IsAssignableFrom(petType)) { Console.WriteLine("Invalid species selected!"); return; } // 创建类实例并转为Pet基类类型 Pet petInstance = (Pet)Activator.CreateInstance(petType); petInstance.Name = petName; Console.WriteLine($"You have selected: {className}"); petInstance.MakeSound(); } public string GetName() { Console.WriteLine("What is your pet's name?"); return Console.ReadLine()?.Trim() ?? "Unknown"; } }
关键说明
- 类型匹配:用户输入的小写物种名需要转为类名格式(首字母大写),确保
Type.GetType能找到对应类;如果类在特定命名空间下,要拼接命名空间前缀。 - 类型校验:通过
typeof(Pet).IsAssignableFrom(petType)校验目标类是否为Pet子类,避免创建无关类。 - 实例统一操作:将创建的实例转为Pet基类类型,即可统一调用基类属性和方法。
- 异常处理(可选):如果需要更严谨,可以给
Activator.CreateInstance添加try-catch块,处理无参构造函数缺失等创建失败的情况。
内容的提问来源于stack exchange,提问作者Lisa
相关产品推荐
相关产品推荐

