技术开发 频道

封装 if/else、swith/case及while

        使用If扩展的代码中用了lambda表达式,如果前面的“p=>p.”能去掉的话,看起来就比较舒服了!编译器通过类型及上下文推演,应该可以做得到吧!

  给出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();
        }

  对引用类型我们可以使用Action,也以使用链式编程的方式将多个If串起来。

  但对值类型来说,就要用Func了,每次返回一个新的值 :

public static T If<T>(this T t, Predicate<T> predicate, Func<T, T> func) where T : struct
        {
            
return predicate(t) ? func(t) : t;
        }
0
相关文章