Re: Dynamic casting at runtime
- From: liko81@xxxxxxxxx
- Date: 21 Aug 2006 08:11:54 -0700
DaTurk wrote:
Hi,
This is a question brought about by a solution I came up with to
another question I had, which was "Dynamic object creation". So, I'm
curious if you can dynamically cast an object. If you have two object
which have a common base class, they can both be cast up to the base
class, but if either of the child classes have unuque methods you will
not be able to access them. Now I know about late binding and all that
stuff, but I need a much more light weight solution.
So I was hoping to have an instance of the base class, and cast it
between the children depending on what's decided during runtime. But
I'm not sure how to represent the class so it can be cast, and chaged.
To the best of my knowledge, you don't need to. Using the
Activator.CreateInstance() function, you retrieve an instance of type
Object; however, that Object knows what specific class it was created
from (thanks to the same metadata that allowed you to create it in the
first place). You really don't even need to cast it to the base class,
though it can help you understand what you've done later.
The caveat with this is that, having dynamically created it, you cannot
statically access members on this class unless you cast to a
non-abstract base class that at least "stubs" the member. So instead,
keep going with reflection.
Object newClass;
string className = 'myClass';
string methodName = 'myMethod';
string propertyName = 'myProperty';
string nameSpace = 'myClasses';
Assembly myAssembly;
ObjectHandler myObjHandler;
PropertyInfo _property;
MethodInfo _method;
Type myType;
//Get the assembly by calling GetExecutingAssembly() or LoadAssembly()
myAssembly = Assembly.GetExecutingAssembly();
myObjectHandler = Activator.CreateInstance(myAssembly.FullName,
nameSpace);
newClass = myObjectHandler.Unwrap();
//This is the code you need
myType = newClass.GetType() //this will return a myClass-instantiated
Type
_property = myType.GetProperty(propertyName); //gets property info
_property.SetValue(newClass, "value", null);
this should get no compile errors, and the system will do what it needs
to at runtime. No, it's not a static call, but it's far more readable
and maintainable than a switch statement for every object you'd expect
to create (read: every class derived from that base class). Besides,
casting a class to an "endpoint" derived class is required only if
you're going to place it in a variable of that type, which would have
to be statically declared.
.
- Follow-Ups:
- Re: Dynamic casting at runtime
- From: DaTurk
- Re: Dynamic casting at runtime
- References:
- Dynamic casting at runtime
- From: DaTurk
- Dynamic casting at runtime
- Prev by Date: Re: Setting StringBuilder.Length not behaving per documentation
- Next by Date: Overwrite image
- Previous by thread: Re: Dynamic casting at runtime
- Next by thread: Re: Dynamic casting at runtime
- Index(es):
Relevant Pages
|