C#命名规则和编码规范
1. 用Pascal規則來命名屬性、方法、事件和類名
| 1 2 3 4 5 6 | public class HelloWorld { public void SayHello(string name) { } } |
Pascal規則是指名稱中單詞的首字母大寫 ,如EmployeeSalary、 ConfimationDialog、PlainTextEncoding。
2. 用Camel規則來命名成員變量、局部變量和方法的參數
| 1 2 3 4 5 6 7 8 9 | public class Product { private string productId; private string productName; public void AddProduct(string productId,string productName) { } } |
Camel規則類似于Pascal規則 ,但名稱中第一個單詞的首字母不大寫 ,如employeeSalary、 confimationDialog、plainTextEncoding。
3. 不要使用匈牙利命名法
不要給成員變量加任何前綴(如、m、s_等等)。如果想要區分局部變量和成員變量,可以使用this關鍵字。
4. 不要將常量或者只讀變量的變量名全部大寫,而使用Pascal規則來命名
| 1 2 3 4 5 | // Correct public static const string ShippingType = "DropShip"; // Avoid public static const string SHIPPINGTYPE = "DropShip"; |
5. 接口的名稱一般以大寫I作前綴
| 1 2 3 4 | public interface IConvertible { byte ToByte(); } |
6. 自定義的屬性以Attribute結尾
| 1 2 3 | public class TableAttribute:Attribute { } |
7. 自定義的異常以Exception結尾
| 1 2 3 4 | public class NullEmptyException:Exception { } |
8. 類的命名。用名詞或名詞短語來命名類名
| 1 2 3 4 5 6 7 8 9 | public class Employee { } public class BusinessLocation { } public class DocumentCollection { } |
9. 方法的命名。一般將其命名為動賓短語
| 1 2 3 4 5 6 7 8 9 | public class File { public void CreateFile(string filePath) { } public void GetPath(string path) { } } |
10. 局部變量的名稱要有意義
不要直接用用i,j,k,l,m,n,x,y,z等做變量名,但for循環除外
11. 代碼分塊
所有的成員變量聲明在類的頂端,用一個換行把它和方法分開。同時可以使用成對的#region...#endregion標記,方便折疊。
12. 布爾型變量或者方法一般可以用is、can、has或者should做前綴。如,isFinished, canWork等。
13. 一般 C# 的編碼風格要求花括號{另起一行,不要直接跟在類名和方法后面。
| 1 2 3 4 | public Sample() { // TODO: 在此處添加構造函數邏輯 } |
14. 可以用縮寫作為UI元素的前綴
常見UI組件的一般縮寫形式:
| 1 2 3 4 | Label --> lbl、Text --> txt、Button --> btn Image --> img、 Widget --> Wgt、 List --> lst、CheckBox --> chk Hyperlink --> lnk、Panel --> pnl、Table --> tab ImageButton --> imb |
?
15. 判斷條件是一個布爾變量時不要使用==進行條件判斷
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // 不友好的寫法 private bool isFinished = true; if(isFinished == true) { // ... } // 正確的寫法 private bool isFinished = true; if(isFinished) { // ... } ``` ### 16. 慎用縮寫 變量名是一個單詞的盡量不要縮寫,多單詞組成的變量名可適當縮寫。 ### 17. 在類的頂部聲明所有的成員變量,靜態變量聲明在最前面 ```csharp // Correct public class Account { public static string BankName; public static decimal Reserves; public string Number {get; set;} public DateTime DateOpened {get; set;} public DateTime DateClosed {get; set;} public decimal Balance {get; set;} // Constructor public Account() { // ... } } |
18. 方法的書寫規范
如果一個方法超過25行,就需要考慮是否可以重構和拆分成多個方法。方法命名要見名知意,好的方法名可以省略多余的注釋。方法功能盡量單一。
19. 其他
補充兩條:
參考文章:
from:https://davidsheh.github.io/2016/03/10/C_Sharp%E5%91%BD%E5%90%8D%E8%A7%84%E5%88%99%E5%92%8C%E7%BC%96%E7%A0%81%E8%A7%84%E8%8C%83/?
總結
以上是生活随笔為你收集整理的C#命名规则和编码规范的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#String与string大小写的区
- 下一篇: C#变量名重构快捷键