简体   繁体   中英

Dynamic Typeof in C#

I am having trouble writing a typeof statement which would be using a variable from a config file the code is like this

Type t = new typeof ("My.other.class" + configValue[0]);

configValue being the dynamic value I get from the app.config file.

The error I get is "type expected" it is fine if I type out the class directly so I am assuming my formatting is incorrect. How should this be written?

The typeof keyword is for compile-time use. Use the Type.GetType(string) API instead.

Is this what you're looking for?

Type t = Type.GetType("spork");
object myspork = Activator.CreateInstance(t);

To do this using just a namespace and class name (like in the question), you'll also need to know which assembly contains the class.

If the currently running assembly (or mscorlib) contains the Type, then you can use Type.GetType(string) to get the Type.

If the Type is contained in a different assembly (ie: a library), then you'll need to use Assembly.GetType instead. This requires having an Assembly instance, however, which can be retrieved via Assembly.Load, or using another type within the assembly.

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.

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