Thursday

Delegate and Event

namespace Delegate_Event_Test
{
class Figure
{
private float m_xPos =0;
private float m_yPos = 0;
private float m_zPos = 0;
private float m_wPos = 0;

public Figure(float a, float b, float c, float d)
{
m_xPos = a;
m_yPos = b;
m_zPos = c;
m_wPos = d;
}

public void InvertX()
{
Console.WriteLine("X Before : {0}", m_xPos);
m_xPos = -m_xPos;
//Inverted("inverted by z-axis");
Console.WriteLine("X After : {0}", m_xPos);
}

public void InvertY()
{
Console.WriteLine("Y Before : {0}", m_yPos);
m_yPos = -m_yPos;
Inverted("inverted by y-axis");
Console.WriteLine("Y After : {0}", m_yPos);
}

public void InvertZ()
{
Console.WriteLine("Z Before : {0}", m_zPos);
m_zPos = -m_zPos;
Inverted("inverted by z-axis");
Console.WriteLine("Z After : {0}", m_zPos);
}

public void InvertW()
{
Console.WriteLine("W Before : {0}", m_zPos);
m_wPos = -m_wPos;
Inverted("inverted by w-axis");
Console.WriteLine("W After : {0}", m_zPos);
}

public delegate void FigureHandler(String str);
public static event FigureHandler Inverted;
}

class TestClass
{
public delegate void FigureDelegate();

static void Main(string[] args)
{
Figure figure = new Figure(10, 20, 30, 40);
FigureDelegate AxisChange_Delg;
AxisChange_Delg = new FigureDelegate(figure.InvertZ);

// Declare 3 delegates of FigureDelegate type and attach to these
// elements our three methods from Figure class.
// Now, every delegate keeps the address of the attached function.
Console.WriteLine("Choose a axis to change (x, y, z): ");
String ans = Console.ReadLine();

switch (Convert.ToChar(ans))
{
case 'x':
AxisChange_Delg = new FigureDelegate(figure.InvertX);
break;
case 'y':
AxisChange_Delg = new FigureDelegate(figure.InvertY);

break;
case 'z':
AxisChange_Delg = new FigureDelegate(figure.InvertZ);
break;
}

AxisChange_Delg();


Console.WriteLine("\n");
Figure.Inverted += new Delegate_Event_Test.Figure.FigureHandler(OnFigureInverted);

figure.InvertW();

Console.ReadLine();
}

private static void OnFigureInverted(string msg)
{
Console.WriteLine("Figure was {0}", msg);
}
}
}



The above shows how to use delegate in C#. Delegate is similar to function pointer in C language.
In the case above, AxisChange_Delg is assigned a function() depending on the selection made by user.
AxisChange_Delg is then called.

The last part of the program shows how to use event.

No comments:

Post a Comment