There are two easy ways to achieve this:
- with an instance of
Parent
passed toChild
- use inheritance and a virtual method in
Parent
but do not override it inChild
The first one can be achieved like this:
class Parent {
Child c = new Child(this);
public void Func(){ ... }
}
public class Child()
{
private Parent _parent;
public Child(Parent parent)
{
_parent = parent;
}
public void SomeRandomMethod()
{
if (_parent != null)
_parent.Func();
}
}
The second option would look like this:
class Parent {
Child c = new Child();
public virtual void Func(){ ... }
}
class Child : Parent
{
public void SomeRandomMethod()
{
Func(); //because the child hasn't overridden this the method in the parent will get called
}
}
Edit:
Based on your updated requirements, here is a (very!) rough semi-pseudocode example using a delegate that is injected into the Logic
class. There are a number of ways this code could be structured. I’ve also assumed that you’ll need to pass multiple parameters to the Draw()
function so I’ve encapsulated that in an object. I also returned a bool from that method – if no return is necessary then change the Func<DrawingParameters, bool>
to Action<DrawingParameters>
.
public class Ui
{
public Ui()
{
var l = new Logic() { DrawingMethod = Draw } ;
}
public bool Draw(DrawingParameters dp)
{
//do your drawing
return true;
}
}
public class Logic
{
public Func<DrawingParameters, bool> DrawingMethod { private get; set; }
public void DoCalculationsAndDraw()
{
var drawingParameters = new DrawingParameters();
//do your calculations, set values in drawingParameters...
DrawingMethod?.Invoke(drawingParameters);
}
}
public class DrawingParameters
{
public Point StartPoint { get; set; }
public Point EndPoint { get; set; }
//etc.....
}
3
solved What is the right way to call function from a class that does not implement the function class? [closed]