Base Method Calling Child Methods

G

Guest

The code below is pretty simple. Calling Talker() in the parent returns
"Parent", and calling Talker() in the child returns "Child".

I'm wondering how I can modify the code so that a call to the Talker() in
Parent will call the Talker() method in every child class. The kicker is that
I have many different Child classes, and not all Child classes will be loaded
when Talker() in the Parent is called.

Thanks,
Randy


class Parent
{
public virtual string Talker()
{
return "Parent";
}
}

class Child : Parent
{
public override string Talker()
{
return "Child";
}
}
 
P

Peter Duniho

The code below is pretty simple. Calling Talker() in the parent returns
"Parent", and calling Talker() in the child returns "Child".

I'm wondering how I can modify the code so that a call to the Talker()in
Parent will call the Talker() method in every child class. The kicker is
that I have many different Child classes, and not all Child classes will
be loaded when Talker() in the Parent is called.

There is no language construct that you can use to do this implicitly.
Also, your question isn't very clear. In your example, you return a
value. What does it mean for a single caller to the Talker() method to be
returned multiple values? Do you mean to concatenate the results? Also,
do you want every instance of every child class to be called? Or do you
simply want a single static method that is only called when at least one
child instance exists? Do you also want the Parent class to be included
or not? Or something entirely different from any of those options?

As an example solution, let's assume that you want every child instance to
be called, you _don't_ want the Parent included, and that you want to
concatenate the return values:

You could certainly write your code so that the Parent class has a static
member that is a collection of references to each instance of every Child,
and then in the Talker() method you would iterate over that collection.
But that would require each of the classes derived from Parent to
cooperate and add the constructed instance to the Parent's collection
whenever you create one.

For example (ignoring the inefficiency of directly concatenating the
strings rather than using the StringBuilder class):

class Parent
{
static protected Collection<Parent> _grparentChildren;

public virtual string Talker()
{
string strReturn = "";

foreach (Parent parentChild in _grparentChildren)
{
strReturn = strReturn + parentChild.Talker();
}

return strReturn;
}

class Child : Parent
{
public Child()
{
_grparentChildren.Add(this);
}

public override string Talker()
{
return "Child";
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top