C#编码规范和命名规则


命名

对于理解应用程序的逻辑流,命名方案是最有影响力的一种帮助。名称应该说明“什么”而不是“如何”。通过避免使用公开基础实现(它们会发生改变)的名称,可以保留简化复杂性的抽象层。例如,可以使用 GetNextStudent(),而不是 GetNextArrayElement()

命名原则是:选择正确名称时的困难可能表明需要进一步分析或定义项的目的。使名称足够长以便有一定的意义,并且足够短以避免冗长。唯一名称在编程上 仅用于将各项区分开。表现力强的名称是为了帮助人们阅读;因此,提供人们可以理解的名称是有意义的。不过,请确保选择的名称符合适用语言的规则和标准。

以下几点是推荐的命名方法。

例程

  • 避免容易被主观解释的难懂的名称,如对于例程的 AnalyzeThis(),或者对于变量的 xxK8。这样的名称会导致多义性,而不仅仅是抽象。
  • 在面向对象的语言中,在类属性的名称中包含类名是多余的,如 Book.BookTitle。而是应该使用 Book.Title
  • 使用动词-名词的方法来命名对给定对象执行特定操作的例程,如 CalculateInvoiceTotal()
  • 在允许函数重载的语言中,所有重载都应该执行相似的函数。对于那些不允许函数重载的语言,建立使相似函数发生关系的命名标准。

变量

  • 只要合适,在变量名的末尾追加计算限定符(AvgSumMinMaxIndex)。
  • 在变量名中使用互补对,如 min/max、begin/end 和 open/close。
  • 鉴于大多数名称都是通过连接若干单词构造的,请使用大小写混合的格式以简化它们的阅读。另外,为了帮助区分变量和例程,请对例程名称使用 Pascal 大小写处理 (CalculateInvoiceTotal),其中每个单词的第一个字母都是大写的。对于变量名,请使用 camel 大小写处理 (documentFormatType),其中除了第一个单词外每个单词的第一个字母都是大写的。
  • 布尔变量名应该包含 Is,这意味着 Yes/No 或 True/False 值,如 fileIsFound
  • 在命名状态变量时,避免使用诸如 Flag 的术语。状态变量不同于布尔变量的地方是它可以具有两个以上的可能值。不是使用 documentFlag,而是使用更具描述性的名称,如 documentFormatType
  • 即使对于可能仅出现在几个代码行中的生存期很短的变量,仍然使用有意义的名称。仅对于短循环索引使用单字母变量名,如 ij
  • 不要使用原义数字或原义字符串,如 For i = 1 To 7。而是使用命名常数,如 For i = 1 To NUM_DAYS_IN_WEEK 以便于维护和理解。

  • 在命名表时,用单数形式表示名称。例如,使用 Employee,而不是 Employees
  • 在命名表的列时,不要重复表的名称;例如,在名为 Employee 的表中避免使用名为 EmployeeLastName 的字段。
  • 不要在列的名称中包含数据类型。如果后来有必要更改数据类型,这将减少工作量。

Microsoft SQL Server

  • 不要给存储过程加 sp 前缀,这个前缀是为标识系统存储过程保留的。
  • 不要给用户定义的函数加 fn_ 前缀,这个前缀是为标识内置函数保留的。
  • 不要给扩展存储过程加 xp_ 前缀,这个前缀是为标识系统扩展存储过程保留的。

杂项

  • 尽量减少使用缩写,而是使用以一致方式创建的缩写。缩写应该只有一个意思;同样,每个缩写词也应该只有一个缩写。例如,如果用 min 作为 minimum 的缩写,那么在所有地方都应这样做;不要将 min 又用作 minute 的缩写。
  • 在命名函数时包括返回值的说明,如 GetCurrentWindowName()
  • 与过程名一样,文件和文件夹的名称也应该精确地说明它们的用途。
  • 避免对不同的元素重用名称,如名为 ProcessSales() 的例程和名为 iProcessSales 的变量。
  • 在命名元素时避免同音异义词(如 write 和 right),以防在检查代码时发生混淆。
  • 在命名元素时,避免使用普遍拼错的词。另外,应清楚区域拼写之间存在的差异,如 color/colour 和 check/cheque。
  • 避免用印刷标记来标识数据类型,如用 $ 代表字符串或用 % 代表整数。

软件文档以两种形式存在:外部的和内部的。外部文档(如规范、帮助文件和设计文档)在源代码的外部维护。内部文档由开发人员在开发时在源代码中编写的注释组成。

不考虑外部文档的可用性,由于硬拷贝文档可能会放错地方,源代码清单应该能够独立存在。外部文档应该由规范、设计文档、更改请求、错误历史记录和使用的编码标准组成。

内部软件文档的一个难题是确保注释的维护与更新与源代码同时进行。尽管正确注释源代码在运行时没有任何用途,但这对于必须维护特别复杂或麻烦的软件片段的开发人员来说却是无价的。

以下几点是推荐的注释方法:

  • 如果用 C# 进行开发,请使用 XML 文档功能。有关更多信息,请参见:XML 文档
  • 修改代码时,总是使代码周围的注释保持最新。
  • 在每个例程的开始,提供标准的注释样本以指示例程的用途、假设和限制很有帮助。注释样本应该是解释它为什么存在和可以做什么的简短介绍。
  • 避免在代码行的末尾添加注释;行尾注释使代码更难阅读。不过在批注变量声明时,行尾注释是合适的;在这种情况下,将所有行尾注释在公共制表位处对齐。
  • 避免杂乱的注释,如一整行星号。而是应该使用空白将注释同代码分开。
  • 避免在块注释的周围加上印刷框。这样看起来可能很漂亮,但是难于维护。
  • 在部署之前,移除所有临时或无关的注释,以避免在日后的维护工作中产生混乱。
  • 如果需要用注释来解释复杂的代码节,请检查此代码以确定是否应该重写它。尽一切可能不注释难以理解的代码,而应该重写它。尽管一般不应该为了使代码更简单以便于人们使用而牺牲性能,但必须保持性能和可维护性之间的平衡。
  • 在编写注释时使用完整的句子。注释应该阐明代码,而不应该增加多义性。
  • 在编写代码时就注释,因为以后很可能没有时间这样做。另外,如果有机会复查已编写的代码,在今天看来很明显的东西六周以后或许就不明显了。
  • 避免多余的或不适当的注释,如幽默的不主要的备注。
  • 使用注释来解释代码的意图。它们不应作为代码的联机翻译。
  • 注释代码中不十分明显的任何内容。
  • 为了防止问题反复出现,对错误修复和解决方法代码总是使用注释,尤其是在团队环境中。
  • 对由循环和逻辑分支组成的代码使用注释。这些是帮助源代码读者的主要方面。
  • 在整个应用程序中,使用具有一致的标点和结构的统一样式来构造注释。
  • 用空白将注释同注释分隔符分开。在没有颜色提示的情况下查看注释时,这样做会使注释很明显且容易被找到。

格式

格式化使代码的逻辑结构很明显。花时间确保源代码以一致的逻辑方式进行格式化,这对于您和必须解密源代码的其他开发人员都有帮助。

以下几点是推荐的格式化方法。

  • 建立标准的缩进大小(如四个空格),并一致地使用此标准。用规定的缩进对齐代码节。
  • 在发布源代码的硬拷贝版本时使用 monotype 字体。
  • 在括号对对齐的位置垂直对齐左括号和右括号,如:
    for (i = 0; i < 100; i++)
    {
    ...
    }

    还可以使用倾斜样式,即左括号出现在行尾,右括号出现在行首,如:

    for (i = 0; i < 100; i++){
    ...
    }

    无论选择哪种样式,请在整个源代码中使用那个样式。

  • 沿逻辑结构行缩进代码。没有缩进,代码将变得难以理解,如:
    If ... Then
    If ... Then
    ...
    Else
    End If
    Else
    ...
    End If

    缩进代码会产生出更容易阅读的代码,如:

    If ... Then
    If ... Then
    ...
    Else
    ...
    End If
    Else
    ...
    End If
  • 为注释和代码建立最大的行长度,以避免不得不滚动源代码编辑器,并且可以提供整齐的硬拷贝表示形式。
  • 在大多数运算符之前和之后使用空格,这样做时不会改变代码的意图。但是,C++ 中使用的指针表示法是一个例外。
  • 使用空白为源代码提供结构线索。这样做会创建代码“段”,有助于读者理解软件的逻辑分段。
  • 当一行被分为几行时,通过将串联运算符放在每一行的末尾而不是开头,清楚地表示没有后面的行是不完整的。
  • 只要合适,每一行上放置的语句避免超过一条。例外是 C、C++、C# 或 JScript 中的循环,如 for (i = 0; i < 100; i++)
  • 编写 HTML 时,建立标准的标记和属性格式,如所有标记都大写或所有属性都小写。另一种方法是,坚持 XHTML 规范以确保所有 HTML 文档都有效。尽管在创建 Web 页时需折中考虑文件大小,但应使用带引号的属性值和结束标记以方便维护。
  • 编写 SQL 语句时,对于关键字使用全部大写,对于数据库元素(如表、列和视图)使用大小写混合。
  • 在物理文件之间在逻辑上划分源代码。
  • 将每个主要的 SQL 子句放在不同的行上,这样更容易阅读和编辑语句,例如:
    SELECT FirstName, LastName
    FROM Customers
    WHERE State = 'WA'
  • 将大的复杂代码节分为较小的、易于理解的模块。
------------------------------------------------
Capitalization Styles

Use the following three conventions for capitalizing identifiers.

Pascal case

The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters. For example:

BackColor

Camel case

The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example:

backColor

Uppercase

All letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters. For example:

System.IO
System.Web.UI

You might also have to capitalize identifiers to maintain compatibility with existing, unmanaged symbol schemes, where all uppercase characters are often used for enumerations and constant values. In general, these symbols should not be visible outside of the assembly that uses them.

The following table summarizes the capitalization rules and provides examples for the different types of identifiers.

Identifier Case Example
Class Pascal AppDomain
Enum type Pascal ErrorLevel
Enum values Pascal FatalError
Event Pascal ValueChange
Exception class Pascal WebException
Note   Always ends with the suffix Exception.
Read-only Static field Pascal RedValue
Interface Pascal IDisposable
Note   Always begins with the prefix I.
Method Pascal ToString
Namespace Pascal System.Drawing
Parameter Camel typeName
Property Pascal BackColor
Protected instance field Camel redValue
Note   Rarely used. A property is preferable to using a protected instance field.
Public instance field Pascal RedValue
Note   Rarely used. A property is preferable to using a public instance field.

------------------------------------------------
Case Sensitivity

To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of case sensitivity:

  • Do not use names that require case sensitivity. Components must be fully usable from both case-sensitive and case-insensitive languages. Case-insensitive languages cannot distinguish between two names within the same context that differ only by case. Therefore, you must avoid this situation in the components or classes that you create.
  • Do not create two namespaces with names that differ only by case. For example, a case insensitive language cannot distinguish between the following two namespace declarations.
    namespace ee.cummings;
    namespace Ee.Cummings;
  • Do not create a function with parameter names that differ only by case. The following example is incorrect.
    void MyFunction(string a, string A)
  • Do not create a namespace with type names that differ only by case. In the following example, Point p and POINT p are inappropriate type names because they differ only by case.
    System.Windows.Forms.Point p
    System.Windows.Forms.POINT p
  • Do not create a type with property names that differ only by case. In the following example, int Color and int COLOR are inappropriate property names because they differ only by case.
    int Color {get, set}
    int COLOR {get, set}
  • Do not create a type with method names that differ only by case. In the following example, calculate and Calculate are inappropriate method names because they differ only by case.
    void calculate()
    void Calculate()
------------------------------------------------
Abbreviations:缩写

To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of abbreviations:

  • Do not use abbreviations or contractions as parts of identifier names. For example, use GetWindow instead of GetWin.
  • Do not use acronyms that are not generally accepted in the computing field.
  • Where appropriate, use well-known acronyms to replace lengthy phrase names. For example, use UI for User Interface and OLAP for On-line Analytical Processing.
  • When using acronyms, use Pascal case or camel case for acronyms more than two characters long. For example, use HtmlButton or htmlButton. However, you should capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io.
  • Do not use abbreviations in identifiers or parameter names. If you must use abbreviations, use camel case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word.
------------------------------------------------
避免单独使用下面的关键字
AddHandler AddressOf Alias And Ansi
As Assembly Auto Base Boolean
ByRef Byte ByVal Call Case
Catch CBool CByte CChar CDate
CDec CDbl Char CInt Class
CLng CObj Const CShort CSng
CStr CType Date Decimal Declare
Default Delegate Dim Do Double
Each Else ElseIf End Enum
Erase Error Event Exit ExternalSource
False Finalize Finally Float For
Friend Function Get GetType Goto
Handles If Implements Imports In
Inherits Integer Interface Is Let
Lib Like Long Loop Me
Mod Module MustInherit MustOverride MyBase
MyClass Namespace New Next Not
Nothing NotInheritable NotOverridable Object On
Option Optional Or Overloads Overridable
Overrides ParamArray Preserve Private Property
Protected Public RaiseEvent ReadOnly ReDim
Region REM RemoveHandler Resume Return
Select Set Shadows Shared Short
Single Static Step Stop String
Structure Sub SyncLock Then Throw
To True Try TypeOf Unicode
Until volatile When While With
WithEvents WriteOnly Xor eval extends
instanceof package var        
------------------------------------------------
类型名对照表
C# type name Visual Basic type name JScript type name Visual C++ type name Ilasm.exe representation Universal type name
sbyte SByte sByte char int8 SByte
byte Byte byte unsigned char unsigned int8 Byte
short Short short short int16 Int16
ushort UInt16 ushort unsigned short unsigned int16 UInt16
int Integer int int int32 Int32
uint UInt32 uint unsigned int unsigned int32 UInt32
long Long long __int64 int64 Int64
ulong UInt64 ulong unsigned __int64 unsigned int64 UInt64
float Single float float float32 Single
double Double double double float64 Double
bool Boolean boolean bool bool Boolean
char Char char wchar_t char Char
string String string String string String
object Object object Object object Object
原文地址:https://www.cnblogs.com/linn/p/771630.html