基本类型--委托(二)

 156 C#对委托的支持
基本类型--委托(二)
157对委托链调用进行更多控制
基本类型--委托(二)
基本类型--委托(二)基本类型--委托(二) internal sealed class Light基本类型--委托(二){
基本类型--委托(二)基本类型--委托(二)        
public String SwitchPosition() 基本类型--委托(二){
基本类型--委托(二)            
return "灯关了";
基本类型--委托(二)        }

基本类型--委托(二)    }

基本类型--委托(二)基本类型--委托(二)    
internal sealed class Fan基本类型--委托(二){
基本类型--委托(二)基本类型--委托(二)        
public String Speed()基本类型--委托(二){
基本类型--委托(二)         
throw new InvalidOperationException("风机因过热而报废");
基本类型--委托(二)        }

基本类型--委托(二)    }

基本类型--委托(二)基本类型--委托(二)    
internal sealed class Speaker 基本类型--委托(二){
基本类型--委托(二)基本类型--委托(二)        
public String Volume() 基本类型--委托(二){
基本类型--委托(二)            
return "声音很大";
基本类型--委托(二)        }

基本类型--委托(二)    }

基本类型--委托(二)    
public sealed class Program
基本类型--委托(二)基本类型--委托(二)    
基本类型--委托(二){
基本类型--委托(二)        
//查询以上各个组件状态
基本类型--委托(二)
        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 == nullreturn 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();
基本类型--委托(二)        }

基本类型--委托(二)    }
158C#为委托提供的语法便利
基本类型--委托(二)

转载于:https://www.cnblogs.com/tenghoo/archive/2008/05/27/1208443.html