我有一个字典对象
Dictionary<string, Type> dict = new Dictionary<string, Type>();
我还有一个 BaseClass 和一些子类,例如:ChildClass1、ChildClass2 等。 字典有值:
dict.Add("type1", typeof(ChildClass1));
dict.Add("type2", typeof(ChildClass2));
我的问题是 - 有没有办法做这样的事情:
BaseClass c = new <<get a type from the dict: dict[type1]>>()?
我只是想让我的解决方案更加灵活,但我不确定这是否可行。 谢谢!
最佳答案
var c = (BaseClass)Activator.CreateInstance(dict["type1"]);
关于c# - 将类型作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799738/