Child object calling dynamic-parent method

K

Kelmen Wong

how to work out a design to enable a child object to call its
parent(creator/container) method/property?

Its easy to be done if the child can know/assume its parent, but in my
scenario, many different object can create the same child object,
means the child object's parent is dynamic.

Event is possible, but I need the process in synchornous, as event
process is in asyn.

Class Parent()
{
Child objChild;
Public CallMeBack() {}
}
Class Parent2()
{
Child objChild;
Public CallMeBack() {}
}
Class Parent3()
{
Child objChild;
Public CallMeBack() {}
}

Class Child()
{
? objParent;
objParent.CallMeBack();
}

I attempt to use typecasting and interface, but the Child must be
well-aware of the type of the parent berfore the typecasting.
 
M

Mattias Sjögren

Kelmen,
Event is possible, but I need the process in synchornous, as event
process is in asyn.

No, event handlers are called synchronously by default.


I'd make the parent classes implement a common interface

interface IParent
{
void CallMeBack();
}

and then pass in a reference to it to the Child constructor.



Mattias
 
K

Kelmen Wong

I'm very grateful for the helpful info. Indeed, I have tested the
approach using Interface, it works as expected.

My initial fauilure attempt with testing is because forget to
implement the interface to the parent class. Somehow the .NET IDE
compile it "successfully", so I thought the interface approach doesn't
work. Luckily I found the missed out declaration later. I thought of
using call-back approach, but the info and requirement even confuse me
much more.
 

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