C# switch和case的扩展,大家评价各不相同,其实本人也感觉有点牵强。其中举了一个Swith扩展的应用,今天突然有了新想法,对它改进了一些。所谓“语不惊人死不休”,且看这次的改进如何。
我先把扩展的源代码贴出来,折叠一下,等看完后面的例子和讲解再回来看。
- public static class SwithCaseExtension
- {
- SwithCase#region SwithCase
- public class SwithCase<TCase, TOther>
- {
- public SwithCase(TCase value, Action<TOther> action)
- {
- Value = value;
- Action = action;
- }
- public TCase Value { get; private set; }
- public Action<TOther> Action { get; private set; }
- }
- #endregion
- Swith#region Swith
- public static SwithCase<TCase, TOther> Switch<TCase, TOther>
(this TCase t, Action<TOther> action) where TCase : IEquatable<TCase>- {
- return new SwithCase<TCase, TOther>(t, action);
- }
- public static SwithCase<TCase, TOther> Switch<TInput, TCase, TOther>
(this TInput t, Func<TInput, TCase> selector, Action<TOther> action)
where TCase : IEquatable<TCase>- {
- return new SwithCase<TCase, TOther>(selector(t), action);
- }
- #endregion
- Case#region Case
- public static SwithCase<TCase, TOther> Case<TCase, TOther>
(this SwithCase<TCase, TOther> sc, TCase option, TOther other)
where TCase : IEquatable<TCase>- {
- return Case(sc, option, other, true);
- }
- public static SwithCase<TCase, TOther> Case<TCase, TOther>
(this SwithCase<TCase, TOther> sc, TCase option, TOther other, bool bBreak)
where TCase : IEquatable<TCase>- {
- return Case(sc, c=>c.Equals(option), other, bBreak);
- }
- public static SwithCase<TCase, TOther> Case<TCase, TOther>
(this SwithCase<TCase, TOther> sc, Predicate<TCase> predict, TOther other)
where TCase : IEquatable<TCase>- {
- return Case(sc, predict, other, true);
- }
- public static SwithCase<TCase, TOther> Case<TCase, TOther>
(this SwithCase<TCase, TOther> sc, Predicate<TCase> predict,
TOther other, bool bBreak) where TCase : IEquatable<TCase>- {
- if (sc == null) return null;
- if (predict(sc.Value))
- {
- sc.Action(other);
- return bBreak ? null : sc;
- }
- else return sc;
- }
- #endregion
- Default#region Default
- public static void Default<TCase, TOther>
(this SwithCase<TCase, TOther> sc, TOther other)- {
- if (sc == null) return;
- sc.Action(other);
- }
- #endregion
- }
到现在为止估计大家应该有一个疑问了,原来的C# switch和case中可以使用“break”直接返回,这里是怎么处理的呢?Case还有第三个参数,它用来处理实是否break,为true时break,false时继续下一个Case。个人感觉大多数情况下,符合某个条件后一般不需要继续其它的了,所以重载传入true,即默认break。与C# switch和case是相反的。
【编辑推荐】