How to use a strongly typed dictionary <string, Type> to associate a string with a class

I want to create a dictionary to associate a string with 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 does not accept Dog.

So what is the syntax?

+3
source share
4 answers

.Net has a dedicated class System.Typeused to describe classes / structures / enumerations (of any type) in the system. Dog- this is the class you want to get this information about, in order to get it, you can either get it using only Type, using typeof(Dog), or - if you have an instance Dog, you can usemyDog.GetType();

+4
source

typeof, Type:

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

typeof (),

0

Source: https://habr.com/ru/post/1765610/


All Articles