当前位置:编程学习 > C#/ASP.NET >>

c#扩展方法封装 if/else、swith/case及while

本文探讨如何使用扩展方法封装 if/else、swith/case及while,通过使用这些扩展,写出的代码将使用很少的大括号{ }。扩展的效果如何,还请大家来评判!
声明:本文属于(改)变(形)态篇,只是提出一种想法,所提供的代码也只是示例,可以测试通过,但不完善。

首先我们来对看if/else和swith/case,两者在代码中都用来表达分支结构。这里我们统一封装成一个If扩展:

        public static T If<T>(this T t, Predicate<T> predicate, Action<T> action) where T: class
        {
            if(t == null) throw new ArgumentNullException();
            if (predicate(t)) action(t);
            return t;
        }

 看下面的调用代码,生成一个People的实例,让他吃饱喝足休息好再工作:

        public static void Test1()
        {
            //常规代码
            People people1 = new People { Name = "ldp615", IsHungry = true, IsThirsty = true, IsTired = true };
            if (people1.IsHungry) people1.Eat();
            if (people1.IsThirsty) people1.Drink();
            if (people1.IsTired) people1.Rest();
            people1.Work();
            //使用扩展方法
            People people2 = new People { Name = "ldp615", IsHungry = true, IsThirsty = true, IsTired = true }
                .If(p => p.IsHungry, p => p.Eat())
                .If(p => p.IsThirsty, p => p.Drink())
                .If(p => p.IsTired, p => p.Rest());
            people2.Work();
        }

扩展方法中的If可以使用点“.”链起来,称之“链式编程”,请参见我我随笔《c#链式编程》。
常规代码和使用扩

补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,