新聞中心
C# switch和case的擴(kuò)展,大家評(píng)價(jià)各不相同,其實(shí)本人也感覺有點(diǎn)牽強(qiáng)。其中舉了一個(gè)Swith擴(kuò)展的應(yīng)用,今天突然有了新想法,對(duì)它改進(jìn)了一些。所謂“語不驚人死不休”,且看這次的改進(jìn)如何。

成都創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),嶗山企業(yè)網(wǎng)站建設(shè),嶗山品牌網(wǎng)站建設(shè),網(wǎng)站定制,嶗山網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,嶗山網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
我先把擴(kuò)展的源代碼貼出來,折疊一下,等看完后面的例子和講解再回來看。
- public static class SwithCaseExtension
- {
- SwithCase#region SwithCase
- public class SwithCase
, TOther> - {
- public SwithCase(TCase value, Action
action) - {
- Value = value;
- Action = action;
- }
- public TCase Value { get; private set; }
- public Action
Action { get; private set; } - }
- #endregion
- Swith#region Swith
- public static SwithCase
, TOther> Switch , TOther>
(this TCase t, Actionaction) where TCase : IEquatable - {
- return new SwithCase
, TOther>(t, action); - }
- public static SwithCase
, TOther> Switch , TCase, TOther>
(this TInput t, Func, TCase> selector, Action action)
where TCase : IEquatable- {
- return new SwithCase
, TOther>(selector(t), action); - }
- #endregion
- Case#region Case
- public static SwithCase
, TOther> Case , TOther>
(this SwithCase, TOther> sc, TCase option, TOther other)
where TCase : IEquatable- {
- return Case(sc, option, other, true);
- }
- public static SwithCase
, TOther> Case , TOther>
(this SwithCase, TOther> sc, TCase option, TOther other, bool bBreak)
where TCase : IEquatable- {
- return Case(sc, c=>c.Equals(option), other, bBreak);
- }
- public static SwithCase
, TOther> Case , TOther>
(this SwithCase, TOther> sc, Predicate predict, TOther other)
where TCase : IEquatable- {
- return Case(sc, predict, other, true);
- }
- public static SwithCase
, TOther> Case , TOther>
(this SwithCase, TOther> sc, Predicate predict,
TOther other, bool bBreak) where TCase : IEquatable- {
- 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
, TOther>
(this SwithCase, 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是相反的。
分享名稱:淺析C#switch和case
網(wǎng)站路徑:http://fisionsoft.com.cn/article/cogeooc.html


咨詢
建站咨詢
