[英]How to use strongly-typed like dictionary <string,Type> to associate a string to a class
我想创建一个字典来将字符串与类关联,例如:
"dog" -> Dog class
"cat" -> Cat class
所以我试过这个
public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", Dog);
但添加不接受Dog
。
那么语法是什么?
您应该使用typeof
运算符来获取相应的Type
对象:
public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", typeof(Dog));
在.Net中有一个专用类System.Type
,用于描述系统中的类/结构/枚举(任何类型)。 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.