Chad Myers
11/26/2002 6:52:00 PM
"Jon Skeet" <skeet@pobox.com> wrote in message
news:MPG.184d2e62ce6717129897fb@10.1.1.14...
> cmyers@N0.SP.4M.austin.rr.com wrote:
> > I'd vote for feature.
> >
> > If you wanted to call the GetHashCode on obj's type rather
> > than System.Object, you'd get the MethodInfo from obj's
> > type.
>
> Seems pretty horrible to me - I'd much rather it acted virtually.
>
> One real-world situation where you might want it to behave that way is
if
> you have several plugin classes all deriving from the same base class
(or
> implementing the same interface). You want to call the same method on
> each of them. Rather than having to get the method reflectively for
each
> individual object, it would be easier if you could get the method from
> base class once, and invoke it with a different target each time.
It's not any harder to get the method for each type.
object myPlugin = Activator.CreateIns.... blah blah blah
myPlugin.GetType().GetMethod("Foo").Invoke(...);
> More fundamentally though, I just don't like this kind of behaviour in
> terms of encapsulation. It feels like it's going behind the back of
the
> object in question. Suppose the object has deliberately overridden the
> method in order to do housekeeping and keep its internal state
consistent
> - calling the base class's method could easily break that.
Keep in mind, this is reflection which basically breaks all
encapsulation :)
You should always take care to get the type of the object you're
working with.
Only in special cases where you need to call a method non-virtually
should you use a base type.
> (And yes, I know you can do it in C++. I don't like that either, and
> think it was a good idea to get rid of it from Java and C#.)
Which is why I'm glad you can't do this through normal means.
-c