15.6 C # Delegate support
15.7 more control over delegated chain calls
Internal sealed class Light {
Public String SwitchPosition (){
Return "the light is off ";
}
}
Internal sealed class Fan {
Public String Speed (){
Throw new InvalidOperationException ("the fan is scrapped due to overheating ");
}
}
Internal sealed class Speaker {
Public String Volume (){
Return "sound great ";
}
}
Public sealed class Program
{
// Query the status of the above components
Private delegate String GetStatus ();
Public static void Main ()
{
GetStatus getstatus = null;
Getstatus + = new GetStatus (new Light (). SwitchPosition );
Getstatus + = new GetStatus (new Fan (). Speed );
Getstatus + = new GetStatus (new Speaker (). Volume );
Console. WriteLine (GetStatusReport (getstatus ));
Console. ReadLine ();
}
Private static String GetStatusReport (GetStatus status)
{
If (status = null) return null;
StringBuilder sb = new StringBuilder ();
Delegate [] arrayOfDelegate = status. GetInvocationList ();
Foreach (GetStatus s in arrayOfDelegate)
{
Try
{
Sb. AppendFormat ("{0} {1} {1}", s (), Environment. NewLine );
}
Catch (InvalidOperationException e)
{
Object component = s. Target;
Sb. AppendFormat ("Failed to get status from {1} {2} {0} Error: {3} {0} {0 }",
Environment. NewLine,
(Component = null )? "": Component. GetType () + "."),
S. Method. Name,
E. Message );
}
}
Return sb. ToString ();
}
}
15.8C # syntax convenience for Delegation