C Sharp/Naming
外观
< C Sharp
原因
[编辑]大部分命名标准来自Microsoft .NET Framework库。
习惯
[编辑]Namespace
[编辑]Namespaces使用Pascal命名法 (也称作UpperCamelCase、大驼峰命名法)且没有下划线。例如: MyNewNamespace。3个或更多字母的缩写词也是首字母大写(MyXmlNamespace 代替 MyXMLNamespace)。
Assembly
[编辑]如果一个assembly包含一个namespace,那么二者应该同名。否则,assembly应该使用Pascal命名法。
类和结构
[编辑]使用Pascal命名法,没有下划线,没有前缀C、cls、I。类和它所在的namespace不应该同名。三个或更多字母的缩写使用Pascal命名法,而不应全大写。尽量避免缩写。尽量使用名词。
异常类
[编辑]名字应以Exception结尾。
Interface
[编辑]前缀以I,随后字母大写。例如:IFoo。
函数
[编辑]使用Pascal命名法,不要用下划线,除非事件处理器。尽量避免缩写。
属性和公开的成员变量
[编辑]使用Pascal命名法,不要用下划线。尽量避免缩写。
参数和方法级变量
[编辑]使用Pascal命名法,不要用下划线。尽量避免缩写。
第一个词的首字母也可以小写。
类级的私有或保护变量
[编辑]前缀以下划线,然后使用Pascal命名法。声明时总是给出protected 或 private关键字。
窗体上的控件
[编辑]前缀以控件类型缩写,随后为使用Pascal命名法,不要用下划线。尽量避免缩写。
ASP.Net web form control例子:
| 控件 | 前缀 | 例子 |
|---|---|---|
| Label | lbl | lblSurname |
| TextBox(ASP.Net) | tb | tbSurname |
| TextBox(WinForms) | txt | txtUserName |
| DataGrid | dg | dgResults |
| GridView | gv | gvResults2 |
| Button | btn | btnSave |
| ImageButton | iBtn | iBtnSave |
| Hyperlink | lnk | lnkHomePage |
| ComboBox | cmb | cmbYear |
| DropDownList | ddl | ddlCompany |
| ListBox | lst | lstCompany |
| DataList | dLst | dLstAddress |
| DataSet | ds | dsInvoices |
| DataTable | dt | dtClients |
| DataRow | dr | drUser |
| Repeater | rep | repSection |
| Checkbox | chk | chkMailList |
| CheckBoxList | chk | chkAddress |
| RadioButton | rBtn | rBtnGender |
| RadioButtonList | rBtn | rBtnAgeGroup |
| Image | img | imgLogo |
| Panel | pnl | pnlSevtion |
| PlaceHolder | plh | plhHeader |
| Calendar | cal | calMyDate |
| AdRotator | adr | adrBanner |
| Table | tbl | tblResults |
| [All] Validators | val (N/A) | valCreditCardNumber |
| ValidationSummary | vals (N/A) | valsErrors |
常量
[编辑]使用Pascal命名法,不要用下划线。尽量避免缩写。见.NET Framework Design Guidelines讨论。
例子
[编辑]using System;
namespace MyExampleNamespace
{
public class Customer : IDisposable
{
private string _customerName;
public string CustomerName
{
get
{
return _customerName;
}
set
{
_customerName = value;
_lastUpdated = DateTime.Now;
}
}
private DateTime _lastUpdated;
public DateTime LastUpdated
{
get
{
return _lastUpdated;
}
private set
{
_lastUpdated = value;
}
}
public void UpdateCustomer(string newName)
{
if (!newName.Equals(CustomerName))
{
CustomerName = newName;
}
}
public void Dispose()
{
//Do nothing
}
}
}