[英]How to use strongly-typed like dictionary <string,Type> to associate a string to a class
I want to create a dictionary to associate a string to a class for example: 我想创建一个字典来将字符串与类关联,例如:
"dog" -> Dog class
"cat" -> Cat class
so I tried this 所以我试过这个
public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", Dog);
but Add doesn't accept Dog
. 但添加不接受Dog
。
So what's the syntax ? 那么语法是什么?
In .Net there is a dedicated class, System.Type
, used to describe classes/structures/enums (any type) in the system. 在.Net中有一个专用类System.Type
,用于描述系统中的类/结构/枚举(任何类型)。 Dog
is the class you want this info about, to get it you can either retrieve it using just the Type
by using typeof(Dog)
, or--if you have an instance of Dog
you can use myDog.GetType();
Dog
是你想要这个信息的类,要获得它,你可以使用typeof(Dog)
使用Type
来检索它,或者 - 如果你有一个Dog
实例你可以使用myDog.GetType();
public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", typeOf(Dog));
typeof(Dog)如果Dog是一个对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.