技术开发 频道

封装 if/else、swith/case及while

      下面的Test5是调用:

public static void Test5()
        {
            
string englishName = "apple";
            
string chineseName = englishName.Switch(
                
new string[] { "apple", "orange", "banana", "pear" },
                
new string[] { "苹果", "桔子", "香蕉", "" },
                
"未知"
                );
            Console.WriteLine(chineseName);
        }

  简单清晰!

  最后是一个对while的扩展封装:

public static void While<T>(this T t,  Predicate<T> predicate, Action<T> action) where T: class
        {
            
while (predicate(t)) action(t);
        }

  调用代码:

public static void Test6()
        {
            People people
= new People { Name = "Wretch" };
            people.While(
                p
=> p.WorkCount < 7,
                p
=> p.Work()
                    );
            people.Rest();
        }

  这while扩展中只能执行一个Action,不太好,我们用params改进一下:

public static void While<T>(this T t, Predicate<T> predicate, params Action<T>[] actions) where T : class
        {
            
while (predicate(t))
            {
                
foreach (var action in actions)
                    action(t);
            }
        }

  再来调用,可以在循环中执行多个操作了。

public static void Test7()
        {
            People people
= new People { Name = "Wretch" };
            people.While(
                p
=> p.WorkCount < 7,
                p
=> p.Work(),
                p
=> p.Eat(),
                p
=> p.Drink(),
                p
=> p.Rest()
                    );
            people.Rest();
        }

  当然前面的If也可以这样的,这里只写出一个:

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

  不使用 params,你就要显示声明一个Action的集合了!关于params, 在我的随笔《改进 Scottgu 的 "In" 扩展 》有说明。

  查看原文

0
相关文章