xXZexxMooreXx
Member
- Joined
- Dec 28, 2014
- Messages
- 5
- Programming Experience
- Beginner
I've been at it a week, and yet I feel worse off than when I heard about delegates and events. The biggest issue I'm having is that the videos and books do a real good job at presenting the syntax and basic ideas behind them, but the contrived examples are really killing me when it comes to being able to use them for myself.
I thought a good example of driving it two concepts home were a simple console based application that had a Person, Phone and SwitchBoard class. My thinking was that the Phone would publish two different events, one based on an outgoing call to the SwitchBoard, and one broadcast to a Person/Persons that are listening for the their phone to ring. Also, my thinking was that the SwitchBoard would publish an event for the proper phone on the other end.
I do believe I was able to make it work between the Phone and Person, but once throwing in the SwitchBoard, things went south from there.
I thought a good example of driving it two concepts home were a simple console based application that had a Person, Phone and SwitchBoard class. My thinking was that the Phone would publish two different events, one based on an outgoing call to the SwitchBoard, and one broadcast to a Person/Persons that are listening for the their phone to ring. Also, my thinking was that the SwitchBoard would publish an event for the proper phone on the other end.
I do believe I was able to make it work between the Phone and Person, but once throwing in the SwitchBoard, things went south from there.
C#:
class Person
{
public Person(Phone p)
{
p.IncomingCallEvent += OnRecieveCall;
}
void OnRecieveCall()
{
Console.WriteLine("You're Phone Is Ringing...");
}
}
class Phone
{
public delegate void IncomingCallHandler();
public event IncomingCallHandler IncomingCallEvent;
public delegate void OutGoingCallHandler(Phone p);
public event OutGoingCallHandler OutGoingCallEvent;
public string Number { get; set; }
public Phone(SwitchBoard sb)
{
sb.phoneDirectory.Add(this);
}
void OnCall()
{
if (IncomingCallEvent != null)
IncomingCallEvent();
}
void OnOutGoingCall()
{
if (OutGoingCallEvent != null)
{
OutGoingCallEvent(this);
}
}
}
class SwitchBoard
{
public delegate void IncomingHandler();
public event IncomingHandler IncomingEvent;
public SwitchBoard(Phone p)
{
phoneDirectory = new List<Phone>();
p.OutGoingCallEvent += OnIncomingCall;
}
public List<Phone> phoneDirectory;
void OnIncomingCall(Phone phone)
{
}