新手C#代碼簡潔性—代碼篇

來源:互聯網
上載者:User

標籤:ant   簡潔   地方   可讀性   部分   案例   代碼   ret   link   

1.合并相似代碼:
牢記心法:只要螢幕上有任何兩部分代碼看上去相似,則一定有合并辦法
例子:
if (!result.Contains("true"))
{
_repSFC.GrantAuthorityToRole(authority, role, false);
}
if (result.Contains("true"))
{
_repSFC.GrantAuthorityToRole(authority, role, true);
}
改後:

_repSFC.GrantAuthorityToRole(authority, role,
result.Contains("true"));

2.多用?是:否 文法:


另一個小案例:

if (Misc == null)
return SFCCatches.LinkP2Cs.Where(i => i.P == p && i.C ==
c);
else
return SFCCatches.LinkP2Cs.Where(i => i.P == p && i.C ==
c && i.Misc == Misc);
改後:

return SFCCatches.LinkP2Cs.Where(i => i.P == p && i.C == c &&
(Misc == null ? true : i.Misc == Misc));
有時候感覺這種寫法有點花哨,但是習慣以後,實際可讀性要高得多,尤其如果單
行代碼挺長的時候。

3.延遲分支
if (...)

{

A();

B();

}

else

{

A();

C();

}

改後:
A();

if (...)

{

B();

}

else

{

C();

}
心法是:任何兩個地方看上去相似,就可以簡化。
技法是:相同部分放在分支前或後,不同部分才是分支。

新手C#代碼簡潔性—代碼篇

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.