Jee*_*87c 3 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 { }
public class Child1 : Parent { }
public class Child2 : Parent { }
public class Child3 : Parent { }
Run Code Online (Sandbox Code Playgroud)
我不想存储实例,而是存储类类型.
编辑:对不起我对我想要做的事情的错误解释.我正在寻找一种存储类型的方法,并确保此类型继承父类.我希望是类型安全的,并确保商店类型是Parent的子类.唯一的办法,就是现在,我想到如何做到这一点就是在这里创建我自己的IDictionary实现.但这不是我想要的.我想这样做
Dictionary<string, typeof(Parent)> dict = ...
Run Code Online (Sandbox Code Playgroud)
任何的想法?
我想当Dictionary<string, Type>你添加一些你应该做的东西时,你只想使用它;
dict.Add("key1", typeof(Child1));
Run Code Online (Sandbox Code Playgroud)
编辑:如Avi的回答所述GetType(),如果要在运行时添加Type,可以在实例上使用该方法.如果你在编译时这样做,你通常会typeof在课堂上使用它.