淺析C# switch和case
C# switch和case的擴(kuò)展,大家評(píng)價(jià)各不相同,其實(shí)本人也感覺有點(diǎn)牽強(qiáng)。其中舉了一個(gè)Swith擴(kuò)展的應(yīng)用,今天突然有了新想法,對(duì)它改進(jìn)了一些。所謂“語不驚人死不休”,且看這次的改進(jìn)如何。
我先把擴(kuò)展的源代碼貼出來,折疊一下,等看完后面的例子和講解再回來看。
- 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)在為止估計(jì)大家應(yīng)該有一個(gè)疑問了,原來的C# switch和case中可以使用“break”直接返回,這里是怎么處理的呢?Case還有第三個(gè)參數(shù),它用來處理實(shí)是否break,為true時(shí)break,false時(shí)繼續(xù)下一個(gè)Case。個(gè)人感覺大多數(shù)情況下,符合某個(gè)條件后一般不需要繼續(xù)其它的了,所以重載傳入true,即默認(rèn)break。與C# switch和case是相反的。
【編輯推薦】


















