- 用Pascal規(guī)則來命名屬性、方法租副、事件和類名坐慰。
public class HelloWorld
{
public void SayHello(string name)
{
}
}
Pascal規(guī)則是指名稱中單詞的首字母大寫 ,如EmployeeSalary、 ConfimationDialog用僧、PlainTextEncoding结胀。
- 用Camel規(guī)則來命名成員變量赞咙、局部變量和方法的參數(shù)。
public class Product
{
private string productId;
private string productName;
public void AddProduct(string productId,string productName)
{
}
}
Camel規(guī)則類似于Pascal規(guī)則 ,但名稱中第一個(gè)單詞的首字母不大寫 ,如employeeSalary糟港、 confimationDialog攀操、plainTextEncoding。
不要使用匈牙利命名法秸抚。不要給成員變量加任何前綴(如速和、m、s_等等)剥汤。如果想要區(qū)分局部變量和成員變量颠放,可以使用
this
關(guān)鍵字。不要將常量或者只讀變量的變量名全部大寫秀姐,而使用Pascal規(guī)則來命名慈迈。
// Correct
public static const string ShippingType = "DropShip";
// Avoid
public static const string SHIPPINGTYPE = "DropShip";
- 接口的名稱一般以大寫I作前綴。
public interface IConvertible
{
byte ToByte();
}
- 自定義的屬性以Attribute結(jié)尾省有。
public class TableAttribute:Attribute
{
}
- 自定義的異常以Exception結(jié)尾痒留。
public class NullEmptyException:Exception
{
}
- 類的命名。用名詞或名詞短語來命名類名蠢沿。
public class Employee
{
}
public class BusinessLocation
{
}
public class DocumentCollection
{
}
- 方法的命名伸头。一般將其命名為動(dòng)賓短語。
public class File
{
public void CreateFile(string filePath)
{
}
public void GetPath(string path)
{
}
}
局部變量的名稱要有意義舷蟀。不要直接用用
i
,j
,k
,l
,m
,n
,x
,y
,z
等做變量名恤磷,但for循環(huán)除外。所有的成員變量聲明在類的頂端野宜,用一個(gè)換行把它和方法分開扫步。同時(shí)可以使用成對的
#region...#endregion
標(biāo)記,方便折疊匈子。布爾型變量或者方法一般可以用
is
河胎、can
或者has
做前綴。如虎敦,isFinished, canWork等游岳。一般C#的編碼風(fēng)格要求花括號{另起一行,不要直接跟在類名和方法后面其徙。
public Sample()
{
// TODO: 在此處添加構(gòu)造函數(shù)邏輯
}
- 可以用縮寫作為UI元素的前綴胚迫。常見UI組件的一般縮寫形式:
Label --> lbl、Text --> txt唾那、Button --> btn
Image --> img访锻、 Widget --> Wgt、 List --> lst、CheckBox --> chk
Hyperlink --> lnk朗若、Panel --> pnl恼五、Table --> tab
ImageButton --> imb
- 判斷條件是一個(gè)布爾變量時(shí)不要使用==進(jìn)行條件判斷昌罩。
// 不友好的寫法
private bool isFinished = true;
if(isFinished == true)
{
// ...
}
// 正確的寫法
private bool isFinished = true;
if(isFinished)
{
// ...
}
變量名是一個(gè)單詞的盡量不要縮寫哭懈,多單詞組成的變量名可適當(dāng)縮寫。
在類的頂部聲明所有的成員變量茎用,靜態(tài)變量生命在最前面遣总。
// 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()
{
// ...
}
}
- 如果一個(gè)方法超過25行,就需要考慮是否可以重構(gòu)和拆分成多個(gè)方法轨功。方法命名要見名知意旭斥,好的方法名可以省略多余的注釋。方法功能盡量單一古涧。
參考文章:
http://www.dofactory.com/reference/csharp-coding-standards
https://blogs.msdn.microsoft.com/brada/2005/01/26/internal-coding-guidelines/