C# 如何创建字典来存储子类的类型

C# 如何创建字典来存储子类的类型,c#,inheritance,dictionary,C#,Inheritance,Dictionary,如何创建一个字典来存储继承另一个类的类型(作为值) 例如: Dictionary<String, typeof(Parent)> dict = new Dictionary<string, typeof(Parent)>(); dict["key1"] = typeof(Child1); dict["key2"] = typeof(Child2); dict["key3"] = typeof(Child3); public abstract class Parent {

如何创建一个字典来存储继承另一个类的类型(作为值)

例如:

Dictionary<String, typeof(Parent)> dict = new Dictionary<string, typeof(Parent)>();
dict["key1"] = typeof(Child1);
dict["key2"] = typeof(Child2);
dict["key3"] = typeof(Child3);

public abstract class Parent { }

public class Child1 : Parent { }
public class Child2 : Parent { }
public class Child3 : Parent { }
Dictionary dict=new Dictionary();
dict[“key1”]=typeof(Child1);
dict[“key2”]=typeof(Child2);
dict[“key3”]=typeof(Child3);
公共抽象类父{}
公共类Child1:父{}
公共类Child2:父{}
公共类Child3:父{}
我不想存储实例,而是存储类类型

编辑:很抱歉,我对我想做的事情做了错误的解释。我正在寻找一种存储该类型并确保该类型继承父类型的方法。我希望是类型安全的,并确保存储类型是父级的子级。目前,唯一的方法是创建自己的IDictionary as实现。但那不是我想要的。我想这样做

Dictionary<string, typeof(Parent)> dict = ...
Dictionary dict=。。。

有什么想法吗?

我想你只是想用
字典
然后当你添加一些你应该做的事情

dict.Add("key1", typeof(Child1));
编辑:如Avi的回答中所述,如果要在运行时添加类型,可以在实例上使用
GetType()
方法。如果您在编译时执行此操作,通常会在类中使用
typeof

var dict=new Dictionary;
var dict = new Dictionary<String, Type>;
dict["key1"] = typeof(Child1);
dict[“key1”]=typeof(Child1);
要解决您的问题,您需要通过
System.Reflection
检查您的类型是否继承自
父类。检查此答案以了解更多信息()

还是这个()

编辑:

要提供替代解决方案

var result = System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(t => t.IsSubclassOf(typeof(Parent));

foreach(Type type in result)
{
    dict["key" + n] = type;
    n++;
}
我认为这个问题没有“直接”的解决办法。

使用typeof:

dict["key1"] = typeof(Child1);
或者,如果您有一个实例:

dict["key1"] = instance.GetType();

您需要
typeof
dict[“key1”]=typeof(Child1)如果您需要在运行时对实例执行此操作,您将获得与
instance.GetType()
相同的值。还值得注意的是,类型字典通常是IoC容器的开始。如果您发现自己需要对象生命周期管理功能,可能值得一看Autofac或Ninject这样的功能。这会起作用,但是,我如何确保附加值是父级的子级?我希望是类型安全的。@Jeep87c您不能在一个简单的语句中完成它。您可以创建包装类,因为泛型类型约束是在类级别指定的。例如如果您正在实现一个泛型集合,您可以执行
公共类MyGenericList,其中T:Parent
。或者您可以添加一个扩展方法,该方法在调用add之前强制执行类型约束。。。谢谢您的回答,我将使用包装器查看潜在的解决方案。@Jeep87c重写
Add
方法可能是另一种选择,尽管我没有尝试过,也不知道是否允许。此外,它可能会在其他地方产生负面影响(比如对于没有相同类型限制的词典)。编写一个扩展方法将是非常干净的,您只需检查该类型是否是父类的子类,如果不是抛出和无效参数异常,则调用正常的add。但是,这不会阻止其他开发人员使用普通的add方法将您不想要的类型放入集合中。有没有办法避免if和/或foreach语句?例如,如果有人试图这样做,抛出一个豁免:dict[“key1”]=typeof(SomethingElse);其中有些东西不是父类的子类。
dict["key1"] = typeof(Child1);
dict["key1"] = instance.GetType();