【IT168 技术】本文探讨如何使用扩展方法封装 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;
}
{
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();
}
{
//常规代码
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#链式编程》。
常规代码和使用扩展方法写的代码都在上面,大家比较一下吧。