Fake Inheritance with Delegates


M

Martijn Mulder

You can fake the mechanism of inheritance by passing in a delegate
function to the constructor. The constructor sets the delegate to a
certain named function, Greet() in the example below. By calling Greet()
from an instance of your object, the designated delegate is called. The
same functionallity can be achieved by inheriting a base class and
overriding the virtual Greet()-function.

If this has real-world significance, I dunno


using System;

class PlanetGreeter
{
public delegate void MyDelegate();
public MyDelegate Greet;

public PlanetGreeter(MyDelegate a){
Greet=a;
}

public static void HelloWorld(){
Console.WriteLine("Hello World");
}

public static void HelloVenus(){
Console.WriteLine("Hello Venus");
}

public static void HelloMars(){
Console.WriteLine("Hello Mars");
}

public static void HelloJupiter(){
Console.WriteLine("Hello Jupiter");
}

public static void HelloUranus(){
Console.WriteLine("You said 'Anus'");
}
}


class SolarSystem
{
PlanetGreeter World=new
PlanetGreeter(PlanetGreeter.HelloWorld);

PlanetGreeter Venus=new
PlanetGreeter(PlanetGreeter.HelloVenus);

PlanetGreeter Jupiter=new
PlanetGreeter(PlanetGreeter.HelloJupiter);

PlanetGreeter Mars=new
PlanetGreeter(PlanetGreeter.HelloMars);

PlanetGreeter Uranus=new
PlanetGreeter(PlanetGreeter.HelloUranus);

SolarSystem()
{
World.Greet();
Venus.Greet();
Jupiter.Greet();
Mars.Greet();
Uranus.Greet();
}

static void Main(){new SolarSystem();}
}
 
Ad

Advertisements

B

Ben Voigt [C++ MVP]

Martijn Mulder said:
You can fake the mechanism of inheritance by passing in a delegate
function to the constructor. The constructor sets the delegate to a
certain named function, Greet() in the example below. By calling Greet()
from an instance of your object, the designated delegate is called. The
same functionallity can be achieved by inheriting a base class and
overriding the virtual Greet()-function.

If this has real-world significance, I dunno

I use something like this to achieve a pared-down version of aspect-oriented
programming.
 
Ad

Advertisements

Ad

Advertisements


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