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
.
So what's the syntax ?
You should use the typeof
operator to get the corresponding Type
object:
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. 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();
public Dictionary<String, Type> dic = new Dictionary<String, Type>();
dic.Add("dog", typeOf(Dog));
typeof(Dog)如果Dog是一个对象
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.