C#命名规范

本文详细介绍了C#编程中的命名规范与约定,包括命名规则、编码习惯、数据类型命名、控件类型命名、ADO.NET命名规范、WinFormControl命名规范、WebControl命名规范等,旨在帮助开发者遵循统一的标准进行编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


引用文章地址: http://bitcyj.blog.51cto.com/995375/222505/
MyData 就是一个帕斯卡命名的示例

myData是一个骆驼命名法,它第一个单词的第一个字母小写,后面的单词首字母大写,看起来像一个骆驼

iMyData是一个匈牙利命名法,它的小写的i说明了它的型态,后面的和帕斯卡命名相同,指示了该变量的用途.

变量命名规范:

内联变量 必须一骆驼camel命名法声明:
for example: uName,uPass;

类变量(成员变量) 同上,但一定要以一个下划线开始!
for example: _mySqlConn

常量命名规范:
带有私有访问修饰的常量必须以骆驼命名法声明,并以一个下划线开始,
for example: private int _SHOW_COUNT=20;

带有公有修饰符.受保护修饰符的常量必须以帕斯卡命名法声明,
for example: protected int COUNT=20;

数组必须以骆驼命名法声明 for example: string[5] nameArray;
string[] nameArray=new string[5];
int[] userAge={20,30,21,22,25,24,22};

结构命名规范:
结构必须以帕斯卡命名法声明,用词或者短语作为声明的首选!
for example: public struct StructName{
//结构体!
}

枚举命名规范:
枚举必须以帕斯卡命名规范命名:
for example: public enum WeekDays{
//结构体
}



=============================================================================

数据类型

数据类型简写

标准命名举例

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 shr shrAverage
Single sng sngMaximum
String
str
strFirstName


控件类型缩写示例
Animated buttonanianiMailBox
Buttonbtn
Check boxchkchkReadOnly
ColorDialogclrdlg
Combobox,drop-down list boxcbocboEnglish
CommunicationscomcomFax
ContextMenuctxmnu
Control(used within procedures when the specific type is unknown)ctrctrCurrent
CrystalReportViewercrvw
DatadatdatBiblio
Data griddgddgdTitles
Data listdbldblPublisher
Data repeaterdrpdrpLocation
Data-bound combo boxdbcbodbcboLanguage
Data-bound griddbgrddbgrdQueryResult
Data-bound list boxdblstdblstJobType
Datetime pickerdtpdtpPublished
Directory list boxdirdirSource
DomainUpDowndupd
Drive list boxdrvdrvTarget
ErrorProvidererr
File list boxfilfilSource
Flat scroll barfsbfsbMove
FontDialogfntdlg
FormfrmfrmEntry
FramefrafraLanguage
GaugegaugauStatus
GraphgragraRevenue
GridgrdgrdPrices
GroupBoxgrp
HelpProviderhlp
Hierarchical flexgridflexflexOrders
HScroll barhsbhsbVolume
ImageimgimgIcon
Image comboimgcboimgcboProduct
ImageListilsilsAllIcons
LabellbllblHelpMessage
LinelinlinVertical
LinkLabellnk
List boxlstlstPolicyCodes
ListViewlvwlvwHeadings
MAPI messagempmmpmSentMessage
MAPI sessionmpsmpsSession
MCImcimciVideo
MenumnumnuFileOpen
Month viewmvwmvwPeriod
MonthCalendarmcl
MS ChartchchSalesbyRegion
MS Flex gridmsgmsgClients
MS TabmstmstFirst
NotifyIconnti
NumericUpDownnupd
OLE containeroleoleWorksheet
OpenFileDialogofdlg
PageSetUpDialogpsdlg
Picture boxpicpicVGA
Picture clipclpclpToolbar
PrintDocumentprndoc
PrintPreviewControlppctl
PrintPreviewDialogppdlg
ProgressBarprgprgLoadFile
RadioButtonrbtn
Remote DatardrdTitles
RichTextBoxrtfrtfReport
SaveFileDialogsfdlg
ShapeshpshpCircle
SlidersldsldScale
SpinspnspnPages
Splitterspt
StatusBarstastaDateTime
SysInfosyssysMonitor
TabContrltab
TabStriptabtabOptions
Text boxtxttxtLastName
TimertmrtmrAlarm
ToolbartlbtlbActions
TrackBartrb
TreeViewtretreOrganization
UpDownupdupdDirection
VScroll barvsbvsbRate




1 ADO.NET 命名规范
数据类型数据类型简写标准命名举例
ConnectionconconNorthwind
CommandcmdcmdReturnProducts
ParameterparmparmProductID
DataAdapterdaddadProducts
DataReaderdtrdtrProducts
DataSetdstdstNorthWind
DataTabledtbldtblProduct
DataRowdrowdrowRow98
DataColumndcoldcolProductID
DataRelationdreldrelMasterDetail
DataViewdvwdvwFilteredProducts
2 WinForm Control 命名规范
数据类型数据类型简写标准命名举例
LabellbllblMessage
LinkLabelllblllblToday
ButtonbtnbtnSave
TextBoxtxttxtName
MainMenummnummnuFile
CheckBoxchkchkStock
RadioButtonrbtnrbtnSelected
GroupBoxgbxgbxMain
PictureBoxpicpicImage
PanelpnlpnlBody
DataGriddgrddgrdView
ListBoxlstlstProducts
CheckedListBoxclstclstChecked
ComboBoxcbocboMenu
ListViewlvwlvwBrowser
TreeViewtvwtvwType
TabControltctltctlSelected
DateTimePickerdtpdtpStartDate
HscrollBarhsbhsbImage
VscrollBarvsbvsbImage
TimertmrtmrCount
ImageListilstilstImage
ToolBartlbtlbManage
StatusBarstbstbFootPrint
OpenFileDialogodlgodlgFile
SaveFileDialogsdlgsdlgSave
FoldBrowserDialogfbdlgfgdlgBrowser
FontDialogfdlgfdlgFoot
ColorDialogcdlgcdlgColor
PrintDialogpdlgpdlgPrint
3 WebControl 命名规范
数据类型数据类型简写标准命名举例
AdRotatoradrtExample
ButtonbtnbtnSubmit
CalendarcalcalMettingDates
CheckBoxchkchkBlue
CheckBoxListchklchklFavColors
CompareValidatorvalcvalcValidAge
CustomValidatorvalxvalxDBCheck
DataGriddgrddgrdTitles
DataListdlstdlstTitles
DropDownListdropdropCountries
HyperLinklnklnkDetails
ImageimgimgAuntBetty
ImageButtonibtnibtnSubmit
LabellbllblResults
LinkButtonlbtnlbtnSubmit
ListBoxlstlstCountries
PanelpnlpnlForm2
PlaceHolderplhplhFormContents
RadioButtonradradFemale
RadioButtonListradlradlGender
RangeValidatorvalgvalgAge
RegularExpressionvalevaleEmail_Validator
RepeaterrptrptQueryResults
RequiredFieldValidatorvalrvalrFirstName
TabletbltblCountryCodes
TableCelltblctblcGermany
TableRowtblrtblrCountry
TextBoxtxttxtFirstName
ValidationSummaryvalsvalsFormErrors
XMLxmlcxmlcTransformResults








======================================================================


part2.

C# Coding Standard



一、命名



1.用pascal规则来命名方法和类型. 

public class TextBox

{

public void DataBind()



}

}



2.用camel规则来命名局部变量和方法的参数.

string  userName;

public AddUser(string userId, byte[] password); 



3.所有的成员变量前加前缀 m_

public class Database



public string m_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. 



9.局部变量的名称要有意义.不要用x,y,z等等.

string userName 



10.所有的成员变量声明在类的顶端,用一个换行把它和方法分开. 



11.用有意义的名字命名namespace,如:产品名、公司名. 



12.建议局部变量在最接近使用它时再声明.



13.使用某个控件的值时,尽量命名局部变量. 



14.把引用的系统的namespace和自定义或第三方的分开. 



15.文件名要能反应类的内容,最好是和类同名,一个文件中一个类. 



16.目录结构中要反应出namespace的层次.



17.大括号"{"要新起一行. 

public class AuthorAttribute : Attribute

{





二、编码习惯.

1.用C#预定义的类名,而不要用别名.

string userName; 而不是  System.String userName;

int number; 而不是 System.Int32; 



2.一行不要超过80个字符. 



3.尽量不要手工更改机器生成的代码,若必须更改,一定要改成和机器生成的代码风格一样. 



4.关键的语句(包括声明关键的变量)必须要写注释. 



5.文字常量和数字常量不要硬编码,应该用常量类或枚举代替.



6.不要用goto系列语句. 



7.不要声明public和protected的成员变量,应用property. 



8.不要声明public的event,应用事件访问器.

public class Source 

{

private EventHandler m_NumberChangeEvent; 



public event EventHandler NumberChangeEvent



add

{

m_NumberChangeEvent += value;





remove

{

m_NumberChangeEvent -= value;



}

}



9.类型转换的使用规则.

Animal animal = new  Dog();

Dog dog = animal as Dog;

if (dog != null)



}



10.生成和构建一个长的字符串时,一定要使用StringBuilder,而不用string. 



11.始终使用"{ }"包含if下的语句,即使只有一条语句. 



12.switch语句一定要有default来处理意外情况.



13.尽量不要使用三目运算符 ?  : ,而要使用if语句.



14.尽量不用使用this引用,除非是要调用类中的另一个Constructor. 

public class Person

{

public Person(string name) 

{

}



public Person() : this("Jim")



}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值