繁体   English   中英

如何使用强类型字典 <string,Type> 将字符串与类关联

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM