Re: Dynamic casting at runtime
- From: liko81@xxxxxxxxx
- Date: 21 Aug 2006 14:40:02 -0700
DaTurk wrote:
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.
The reason I want to cast it to the child is because I don't know of
any other way to access the child specific, methods. How would I do
that then?
You can use reflection, or you can call a method that is not abstract
on the base class that you cast to, and the application will know to
use the instance's implementation (this is more a hack than best
practices, and you will still get a compiler error if you try to call
an abstractly-defined member function).
There is another method you can use if you know at compile-time that
the class you will be dealing with is one of a small group (say you're
cataloguing vehicles, and know that the vehicle can only be a Car,
Truck, Van, SUV, Motorcycle, or RV). Call the object's GetType()
method, then compare what that returns to the results of the typeof()
operator when passed each class that this object could have been. This
allows for a specific cast, but it vastly reduces the maintainability
and utility of the code, as you are specifying limits on the types of
objects that can be used here, and you must change this code to
increase those limits. For instance, to add the ability to catalogue a
Boat, you must implement the Boat object AND change the casting code to
work with a Boat. I would only recommend this for small RAD projects
with a limited lifespan, since it saves code and the expandability is
not an issue.
I described using reflection above, but to summarize, you will call
your object's GetType() member (you don't need to have overridden it)
to obtain a Type object. You then call the GetMethod() method of the
Type object to get a MethodInfo object, and then you call
MethodInfo.Invoke() and pass it the class instance and parameters, and
it will return the method's return value if any. It'll look something
like this:
Object myObject; (instantiated as some derived class)
Type myObjectType;
MethodInfo myMethod;
Object returnValue;
object[] parameterArray;
myObjectType = myObject.GetType();
myMethod = myObjectType.GetMethod("MethodName");
//TODO: initialize parameterArray with all parameters to be passed, in
order
//TODO: set parameterArray to new Object[0] if method doesn't take any
parameters
returnValue = myMethod.Invoke(myObject, parameterArray);
.
- References:
- Dynamic casting at runtime
- From: DaTurk
- Re: Dynamic casting at runtime
- From: liko81
- Re: Dynamic casting at runtime
- From: DaTurk
- Dynamic casting at runtime
- Prev by Date: How do you clean the Recent Projects listbox
- Next by Date: Re: DataGrid
- Previous by thread: Re: Dynamic casting at runtime
- Next by thread: Tree View Question
- Index(es):
Relevant Pages
|