"Paulustrious" <msdn_whoisat_paulcotter.com> a écrit dans le message de
news:
58**********************************@microsoft.com...
| Is it possible to decide on the type of an object at run time. So in
| pseudo-code I am looking for one (or preferably both) of the following....
|
| string s = "SomeExistingClass"
| ClassTypeInString(s) MyThing = new ClassTypeInString(s) ;
|
| ...or....
|
| SomeClass myVar = new SomeClass() // and later on we do...
| ClassTypeOfObject(myVar) MyThing = new ClassTypeOfObject(myVar)
|
| I suspect there is something in System.Reflection. I dipped a toe in
there,
| but the water looks awfully deep for a beginner. I am trying to convert
some
| powerbuilder code and I want the equivalent of...
|
| myObj = Create using sSomeStringVariable
You certainly can use Activator.CreateInstance(...) to do things like this,
it works with either strings or Types.
The practice of using strings to decide runtime behaviour is prone to error
due to mis-spelling, and other things. This style of programming is really a
hangover from the days of interpreters like BASIC, Clipper and others. Why
would you want to use strings to make these decisions ?
OTOH, IMO, you would be better advised to use variables of Type to hold the
type that you want to instantiate.
There is a Design Pattern called Class Factory which is recommended, usually
to create instances of derived classes into an abstract class reference or
an interface reference.
Do you have a hierarchy of classes in mind or just any class that comes
along ?
If the former, then I would recommend that you use Activator.CreateInstance
inside a Class Factory class; if the latter, then I personally would
recommend you redesign the way things are being done.
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer