Reputation: 14379
So here is my setup and the comment shows what I wish to do:
class Process
{
void SomeMethod()
{
// Here I want to call Parent.MethodToCall()
}
}
class Controller
{
Process c = new Process();
void MethodToCall()
{
}
}
Now the Controller.MethodToCall()
will be called many times throughout the lifecycle of the Process
class.
It is only the parent method that needs to be called so I believe that using an event
would be a bit wasteful as I will never be removing the handler and there would only be one invocation.
So the way I am currently using to get around this is like follows:
class Process
{
public Func<void> Method { get; set; }
void SomeMethod()
{
Method();
}
}
class Controller
{
Process c = new Process() { Method = MethodToCall }
void MethodToCall()
{
}
}
First off, the syntax might not be perfect, I quickly knocked it up in notepad.
My question: What is the best way to achieve what I want because what I am doing looks quite messy to be?...or am I thinking about this completely the wrong way in terms of design?
Essentially what I want to do is call a method in the Controller class without making it public, because if it is public, I could simply pass the Controller as a parameter to the Process.
Upvotes: 0
Views: 6436
Reputation: 18843
This should be a good example of how to do that
class Child : Parent
{
private void SomeMethod()
{
base.MethodToCall();
}
}
class Parent
{
Child c = new Child();
protected void MethodToCall()
{
c.MethodToCall();//not sure if you are wanting to call c.MethodToCall();
}
}
Upvotes: 2
Reputation: 16277
class Child
{
Parent parent=null;
public Child(Parent p)
{
parent=p;
}
void SomeMethod()
{
parent.MethodToCall();
}
}
Upvotes: 3
Reputation: 31847
Well, in OOP terms the correct answer would be the following:
class Child : Parent
{
void SomeMethod()
{
base.MethodToCall();
}
}
class Parent
{
protected void MethodToCall()
{
// protected methods are accesible from
// descendants and private from outside
}
}
But you can always avoid inheritance, using aggregation
Upvotes: 1
Reputation: 1708
What you are doing is essentially rolling your own events. Internally, event handlers are just delegates attached to the event, with the one difference that only the owner of the event can raise it.
Upvotes: 0