I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:
First of all, there is a standard method signature in .Net that is typically used for events. The languages allow any sort of method signature at all to be used for events, and there are some experts who believe the convention is flawed (I mostly agree), but it is what it is and I will follow it for this example.
public class ComputerEventArgs : EventArgs
{
Computer computer;
// constructor, properties, etc.
}
class ComputerEventGenerator // I picked a terrible name BTW.
{
public event EventHandler ComputerStarted;
public event EventHandler ComputerStopped;
public event EventHandler ComputerReset;
...
}
class ComputerEventGenerator
{
...
private void OnComputerStarted(Computer computer)
{
EventHandler temp = ComputerStarted;
if (temp != null) temp(this, new ComputerEventArgs(computer)); // replace "this" with null if the event is static
}
}
void OnLoad()
{
ComputerEventGenerator computerEventGenerator = new ComputerEventGenerator();
computerEventGenerator.ComputerStarted += new EventHandler(ComputerEventGenerator_ComputerStarted);
}
private void ComputerEventGenerator_ComputerStarted(object sender, ComputerEventArgs args)
{
if (args.Computer.Name == "HAL9000")
ShutItDownNow(args.Computer);
}
void OnClose()
{
ComputerEventGenerator.ComputerStarted -= ComputerEventGenerator_ComputerStarted;
}
And that's it!
EDIT: I honestly can't figure out why my numbered points all appear as "1." I hate computers.