C#编码规范
1.命名规则与风格(naming conventions and style)
1.1 命名规则
1.1.1 变量命名规范
类型 前缀 示例
Array arr arrShoppingList
Boolean bln blnIsPostBack
Byte byt bytPixelValue
Char chr chrDelimiter
DateTime dtm dtmStartDate
Decimal dec decAverageHeight
Double dbl
dblSizeofUniverse
Integer int intRowCounter
Long lng lngBillGatesIncome
Object obj objReturnValue
Short sht
shtAverage
Single sng sngMaximum
String str strFirstName
1.1.2 控件命名规范
类型 前缀 示例
AdRotator adrt adrtTopAd
Button btn btnSubmit
Calendar cal
calMettingDates
CheckBox chk chkBlue
CheckBoxList chkl chklFavColors
CompareValidator valc valcValidAge
CustomValidator valx valxDBCheck
DataGrid dgrd dgrdTitles
DataList dlst dlstTitles
DropDownList drop dropCountries
HyperLink lnk lnkDetails
Image img imgAuntBetty
ImageButton ibtn ibtnSubmit
Label lbl lblResults
LinkButton lbtn lbtnSubmit
ListBox lst lstCountries
Panel pnl pnlForm2
PlaceHolder plh plhFormContents
RadioButton rad radFemale
RadioButtonList radl radlGender
RangeValidator valg valgAge
RegularExpression vale valeEmail_Validator
Repeater rpt rptQueryResults
RequiredFieldValidator valr valrFirstName
Table tbl tblCountryCodes
TableCell tblc tblcGermany
TableRow tblr tblrCountry
TextBox txt txtFirstName
ValidationSummary vals valsFormErrors
XML xmlc xmlcTransformResults
1.1.3 ADO.NET 控件命名规范
类型 前缀 示例
Connection
conn connNorthwind
Command cmd cmdReturnProducts
Parameter parm parmProductID
DataAdapter da daProducts
DataReader dtr dtrProducts
DataSet ds dsNorthWind
DataTable
dt
dtProduct
DataRow dr drRow98
DataColumn dc dcProductID
DataRelation drel drelMasterDetail
DataView dvw dvwFilteredProducts
1.1.4 命名规则补充
Form=================== = frm
Class=================== cls/C
Module================= mod
GroupBox================ grp
PictureBox============== pic
ComboBox================ cbo
TreeView================ tvw
ListView================ lvw
TabControl============= tab
DateTimePicker======= dtp
Timer=================== tmr
Splitter================ spl
ProgressBar============ pbar
RichTextBox=========== rtf
ImageList============== imgl
ToolBar================= tlb
MenuItem============= mnu
Date==================== dat
Structure=============== udt
Crystal Report========= = rpt
1.1.5 事件处理子程序
The name of an event-handling subroutine will consist of the ID of the control that
rasied the event followed by the type of event being handled. For example, a subroutine
named btnSubmit_Click handles the Click event of a Button control named btnSubmit.
When a control that raises an event is not assigned an ID, the type of the control is
used instead of the ID. For example, the subroutine named Button_Click handles the Click
event of a Button control without an ID.
1.2.编码风格
1 用 pascal 规则来命名方法和类型.
public class TextBox
{
public void DataBind()
{
}
}
2 用 camel 规则来命名局部变量和方法的参数.
string userName;
public AddUser(string userId, byte[] password);
3 所有的成员变量前加前缀 _
public class Database
{
private string _connectionString;
}
4 接口的名称加前缀 I.
interface ICompare
{
int compare();
}
5 自定义的属性以 Attribute 结尾
public class AuthorAttribute : Attribute
{
}
6 自定义的异常以 Exception 结尾
public class AppException : Exception
{
}
7 方法的命名.一般将其命名为动宾短语.
ShowDialog()
CreateFile()
GetPath()
8 代码的缩进.要用 Tab,而不要用 space, 保持严格的缩进:
对缩进使用 3 个空格位
绝不使用不标准的缩进,如 1,2 或 4 个空格位
9 局部变量的名称要有意义.不要用 x,y,z 等等(除用于 For 循环变量中可使用 i,j,k,l,m,n).
string userName
10.建议局部变量在最接近使用它时再声明.
11 所有的成员变量声明在类的顶端,用一个换行把它和方法分开.
public class MyClass
{
int _intNumber;
string _strName;
=
public void SomeMethodl()
{}
public void SomeMethod2()
{}
}
12.用有意义的名字命名 namespace,如:产品名、公司名.
13.避免使用命名空间的完整限定名称,应使用 using 声明替代
14.避免 using 声明放置在命名空间内部
15.将所有的框架命名空间分组,将用户或第三方命名空间放置在其下
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using MyCompany;
using MyControls;
16.使用某个控件的值时,尽量命名局部变量.
17.文件名要能反应类的内容,最好是和类同名,一个文件中一个类或一组关连类.
18.大括号"{"要新起一行.
public class AuthorAttribute : Attribute
{
}
19.用 C#预定义的类名,而不要用在 System 空间内别名.
object 而不是 System.0bject
string 而不是 System.String
int 而不是 System.Int32
20.一行不要超过 80 个字符.
21.尽量不要手工更改机器生成的代码,若必须更改,一定要改成和机器生成的代码风格一样.
22.关键的语句(包括声明关键的变量)必须要写注释.
23.将注释缩拍在与代码缩进同等级的位置上
24.所有的注释应该通过拼写检查.拼错的注释将预示冗余的开发
25.文字常量和数字常量不要硬编码,应该用常量类或枚举代替.
26.不准使用 goto 系列语句.
27.不要声明 public 和 protected 的成员变量,应用 property.
28.不要声明 public 的 event,而应使用事件访问器.
public class Source