简体   繁体   English

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

[英]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 ? 那么语法是什么?

You should use the typeof operator to get the corresponding Type object: 您应该使用typeof运算符来获取相应的Type对象:

public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", typeof(Dog));

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.

相关问题 如何使用强型卫星组件? - How to use strongly-typed satellite assembly? 如何获得从匿名类型的字符串成员到强类型 controller 操作的隐式类型转换? - How can I get implicit type conversions from string members of anonymous types to strongly-typed controller actions? 有没有办法定义现有原始类型(如 `string` 或 `int`)的 C# 强类型别名? - Is there a way to define C# strongly-typed aliases of existing primitive types like `string` or `int`? 如何在启动 class 中使用强类型配置 - How can I use a strongly-typed config within the Startup class 如何将聚合物库与强类型视图一起使用? - How can i use Polymer library with Strongly-Typed View? 如何在服务器标签中使用强类型资源? - How can I use strongly-typed resources in server tags? 转换词典<int, string>强类型 class ICollection 使用 AutoMapper</int,> - Convert Dictionary<int, string> to strongly typed class ICollection Using AutoMapper 类的强类型搜索功能? - Strongly-typed Search functionality for class? Objective-C转换为C#:如果字典是强类型的,如何在C#中使用多个类型的.plist? - Objective-C converting to C#: How can I use a .plist with multiple types in C# if Dictionary is strongly-typed? 字典 <string, object> 到强类型对象 - Dictionary<string, object> to strongly typed object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM