zoukankan      html  css  js  c++  java
  • 基本类型委托(二)

     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#为委托提供的语法便利
  • 相关阅读:
    记录一下我的2017年阅读书单
    大型网站技术架构(二)--大型网站架构演化
    《大型网站技术架构:核心原理与案例分析》读书笔记系列
    过年了,别忘记给家人的礼物
    2017总结
    MyBatis + MySQL返回插入成功后的主键id
    微信公众号问题:{"errcode":40125,"errmsg":"invalid appsecret, view more at http://t.cn/LOEdzVq, hints: [ req_id: kL8J90219sg58 ]"}
    git删除本地分支
    Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十二)Spring集成Redis缓存
    Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十一)redis密码设置、安全设置
  • 原文地址:https://www.cnblogs.com/tenghoo/p/1208443.html
Copyright © 2011-2022 走看看