If one had a class such as 'Painter' and one needed the user to be able to create an instance or instances of this class @ runtime, what's the best way to go about this?
So each time a user clicks a button, we need a new painter object?
Or each time the user enters 'new painter' we need a new painter instance?
You can get a Type
from a string
using Type.GetType
.
Once you've got a Type
object, you can call Activator.CreateInstance
to instantiate it, or call Type.GetConstructors
, choose an appropriate constructor and then invoke it.
Two "gotchas" about Type.GetType
, by the way:
mscorlib
, you need to specify the assembly name as well with version information if it's strongly named If you have a reference to the assembly in question, then Assembly.GetType
can be a simpler approach - you still need to include the namespace though.
I'm guessing that the gist of your question is that the class type is unknown prior to the user's input. Otherwise, if you wanted a new Painter class on each button click, you could simply handle the button click and do " var newpainter = new Painter();
".
So, assuming you need to dynamically create an instance of an unknown type, you can use reflection to do this at runtime.
var newpainter = Activator.CreateInstance(Type.GetType("Painter"), args);
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.