淺析C# switch和case
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
- }
到現(xiàn)在為止估計大家應該有一個疑問了,原來的C# switch和case中可以使用“break”直接返回,這里是怎么處理的呢?Case還有第三個參數(shù),它用來處理實是否break,為true時break,false時繼續(xù)下一個Case。個人感覺大多數(shù)情況下,符合某個條件后一般不需要繼續(xù)其它的了,所以重載傳入true,即默認break。與C# switch和case是相反的。
【編輯推薦】