gpt4 book ai didi

c# - 将类型作为参数传递给函数

转载 作者:行者123 更新时间:2023-11-30 20:10:38 24 4
gpt4 key购买 nike

我有一个字典对象

Dictionary<string, Type> dict = new Dictionary<string, Type>();

我还有一个 BaseClass 和一些子类,例如:ChildClass1ChildClass2 等。字典有值:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com