Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用强类型词典<;字符串,类型>;将字符串与类关联_C# - Fatal编程技术网

C# 如何使用强类型词典<;字符串,类型>;将字符串与类关联

C# 如何使用强类型词典<;字符串,类型>;将字符串与类关联,c#,C#,我想创建一个字典,将字符串与类相关联,例如: "dog" -> Dog class "cat" -> Cat class 所以我试过这个 public Dictionary<String, Type> dic = new Dictionary<String, Type>(); dic.Add("dog", Dog); 公共字典dic=新字典(); dic.添加(“狗”,狗); 但是Add不接受Dog 那么语法是什么呢?您应该使用操作符来获取相应的类型对象

我想创建一个字典,将字符串与类相关联,例如:

"dog" -> Dog class
"cat" -> Cat class
所以我试过这个

public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", Dog);
公共字典dic=新字典();
dic.添加(“狗”,狗);
但是Add不接受
Dog

那么语法是什么呢?

您应该使用操作符来获取相应的
类型
对象:

public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", typeof(Dog));
公共字典dic=新字典();
dic.添加(“狗”,类型(狗));
typeof(Dog),如果Dog是一个对象

公共字典dic=newdictionary();
public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", typeOf(Dog));
dic.添加(“狗”,类型(狗));
在.Net中有一个专用类,
System.Type
,用于描述系统中的类/结构/枚举(任何类型)
Dog
是您想要了解此信息的类,要获取此信息,您可以使用
Type
通过
typeof(Dog)
检索它,或者——如果您有
Dog
的实例,您可以使用
myDog.GetType()