本文介绍了如何实例化一个给定字符串名称的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,我想将它初始化为一个扩展它的类.

I have an abstract class and I want to initalize it to a class that extends it.

我将子类名称作为字符串.

I have the child classes name as a string.

除此之外...

String childClassString;
MyAbstractClass myObject;

if (childClassString = "myExtenedObjectA")
    myObject = new ExtenedObjectA();
if (childClassString = "myExtenedObjectB")
    myObject = new ExtenedObjectB();

我该怎么做?基本上我如何摆脱这里的 if 语句?

How can I do this? Basically how do I get rid of the if statements here?

推荐答案

看 Activator.CreateInstance().

Look at Activator.CreateInstance().

myObject = (MyAbstractClass)Activator.CreateInstance("AssemblyName", "TypeName");

var type = Type.GetType("MyFullyQualifiedTypeName");
var myObject = (MyAbstractClass)Activator.CreateInstance(type);

这篇关于如何实例化一个给定字符串名称的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:53