C#命名规则

1.     命名规则和风格 Naming Conventions and Style

1.        类和方法名采用Pascal风格
    Use Pascal casing for typeand method names
    public class SomeClass
    {
       public SomeMethod(){}
    }

2.        局部变量和方法参数采用camel风格
    Use camel casing for local variablenames and method arguments
    int number;
    void MyMethod(int someNumber)
    {}

3.        接口名采用I作为前缀
    Prefix interface name with I 
    interface IMyInterface
    {..}

4.        私有成员变量采用m_作为前缀
    Prefix private member variables withm_
    public class SomeClass
    {
       private int m_Number;
    }

5.        自定义属性类名采用Attribute作为后缀
    Suffix custom attribute classes withAttribute. 

6.        自定义异常类名采用Exception作为后缀
    Suffix custom exception classes withException.

7.        采用动词-对象对命名方法,例如ShowDialog()
    Name methods using verb-object pair, such as ShowDialog()

8.        有返回值的方法应该取名表示其返回值,例如GetObjectState()
    Methods with return values should have a name describing thevalue returned, such as GetObjectState().

9.        采用描述性的变量名。
    Use descriptive variable names.
    a) 避免采用单字母的变量名,如i或t;而是采用index或temp。
       Avoid  single character variablenames, such as i or  t. Use  index or temp instead. 
    b) 对public和protected成员避免采用用匈牙利命名法。
       Avoid using Hungarian notation for publicor protected members. 
    c) 不要采用缩写(例如将number缩写为num)。
       Do not abbreviate words (such as numinstead of number).

10.    总是使用C#预定义的类型,而不是使用System命名空间中的别名。例如:采用object不用Object,采用string不用String,采用int不用Int32。
     Always use C# predefined types rather than the aliasesin the  System namespace.
     For example: 
     object NOT Object
     string NOT String
     int    NOT Int32

11.    对于泛型,类型采用大写字母。当处理.NET类型Type时保留后缀Type。
     With generics,  use capital letters for types.Reserve suffixing Type when dealing with the .NET type Type.
     // 正确:
     //Correct:
     public class LinkedList
     // 避免使用:
     //Avoid: 
     public class LinkedList 

12.    采用有意义的命名空间名,例如产品名称或公司名称。
     Use meaningful namespaces suchas the product name or the company name

13.    避免使用类的全称,而是采用using语句。
     Avoid fully qualified typenames. Use the using statement instead. 

14.    避免在命名空间内使用using语句。
     Avoid putting a usingstatement inside a namespace.

15.    将所有framework命名空间名放在一起,后面放自定义或第三方的命名空间名。
     Group all framework namespacestogether and put custom or third party namespaces underneath.
     using System;
     using System.Collections;
     using System.ComponentModel;
     using System.Data;
     using MyCompany;
     using MyControls;

16.    注释缩进和其注释的代码在同一层次。
       Indent comment at the same level ofindentation as the code you are documenting.

17.    所有注释要经过拼写检查。拼写错误的注释表明开发的草率。
      All comments should pass spell checking.Misspelled comments indicate sloppy development. 

18.    所有成员变量应该定义在前面,和属性或方法间空开一行。
      All member variablesshould be declared at the top, with one line separating them from theproperties or methods. 
     public class MyClass
     {
        int m_Number;
        string m_Name;

       public void SomeMethod1()
        {}
        public void SomeMethod2()
        {}
     }

19.    局部变量的定义尽可能靠近它的初次使用。
       Declare a localvariable as close as possible to its first use.

20.    文件名应该体现其包含的类。
       A file name shouldreflect the class it contains.

21.    当使用partial类型且每部分分配一个文件时,以类型名加P和序数命名每个文件。
       When using partial types and allocating apart per file, name each file after the type suffixed with a P and anordinal number:
     //In MyClassP1.cs
     public partial class MyClass
     {}
     //In MyClassP2.cs
     public partial class MyClass
     {}

22.    左大括号总是放在新行中。
       Always place anopen curly brace ({) in a new line.

23.    匿名方法模仿普通方法的布局,和匿名委托定义放在一行。
       With anonymous methods mimic the codelayout of a regular method, aligned with the anonymous delegatedeclaration. 
     a) 遵守将左大括号放在新行的规则。
         Comply with placing an opencurly brace in a new line
     delegate void SomeDelegate(string someString);
     //正确
     //Correct: 
     public void InvokeMethod()
     {
        SomeDelegate someDelegate =delegate(string name)
                                   {
                                      MessageBox.Show(name);
                                   };
        someDelegate("Juval");
     }
     //避免采用:
     //Avoid
     public void InvokeMethod()
     {
        SomeDelegate someDelegate =delegate(string name){MessageBox.Show(name);};
        someDelegate("Juval");
     }

24.    没有参数的匿名方法使用空括号。
       Use empty parenthesis on parameter-lessanonymous methods
     a) 仅当匿名方法可能被用于任何委托时省略括号。
         Omit the parenthesis only ifthe anonymous method could have been used on any delegate.
     delegate void SomeDelegate();
     //Correct 
     SomeDelegate someDelegate1 = delegate()
                                 {
                                    MessageBox.Show("Hello");
                                 };
     //Avoid 
     SomeDelegate someDelegate1 = delegate
                                 {
                                    MessageBox.Show("Hello");
                                 };

2.     编码惯例   Coding Practices

1.        避免在一个文件中放多个类。
    Avoid putting multiple classes in asingle file. 

2.        一个文件应该只对一个命名空间提供类型。避免在同一文件中有多个命名空间。
    A single file should only contribute types to a singlenamespace. Avoid having multiple namespaces in the same file.

3.        避免文件长度超过500(除了机器自动产生的代码)
    Avoid files with more than 500 lines(excluding machine-generated code).

4.        避免方法定义超过25行。
    Avoid methods with more than 25lines.

5.        避免超过5个参数的方法。使用结构传递多个参数。
    Avoid methods with more than 5arguments. Use structures for passing multiple arguments.  

6.        每行应该不超过80个字符。
    Lines should not exceed 80characters.

7.        不要手工编辑任何机器生成的代码。
    Do not manually edit any machinegenerated code. 
    a) 如果修改机器生成的代码,修改代码格式和风格以符合本编码标准。
      If modifying machine generated code, modify theformat and style to match this coding standard.
    b) 尽可能采用partial类以分解出需要维护的部分。
      Use partial classes whenever possible to factorout the maintained portions. 

8.        避免对显而易见的内容作注释。
   Avoid comments that explain theobvious.  
   a) 代码应该是自解释的。 由可读性强的变量和方法组成的好的代码应该不需要注释。
      Code should be self explanatory.  Good codewith readable variable and method names should not require comments.

9.        仅对操作的前提、内在算法等写文档。
    Document only operationalassumptions, algorithm insights and so on.  

10.    避免方法级的文档。
     Avoid method-level documentation.
     a) 对API文档采用大量的外部文档。
         Use extensive externaldocumentation for API documentation.
     b) 方法级注释仅作为对其他开发人员的提示。
         Use method-level comments onlyas tool tips for other developers.

11.    决不要硬编码数值,而总是声明一个常量。
     Never hard-code a numericvalue, always declare a constant instead. 

12.    仅对本来就是常量的值使用const修饰符,例如一周的天数。
     Use the  const directiveonly on natural constants such as the number of days of week. 

13.    避免对只读变量使用const修饰符。在此情况下,采用readonly修饰符。
     Avoid using const on read-only variables. For that,use the readonly directive.
     public class MyClass
     {
        public readonly int Number;
        public MyClass(int someValue)
        {
           Number =someValue;
        }
        public const int DaysInWeek = 7;
     }

14.    对任何假设采用assert。
      Assert every assumption.
      a) 平均地,每5行中就有一行是断言。
        On average, every fifth line is anassertion.
      using System.Diagnostics;
      object GetObject()
      {
            object obj =GetObject();
            Debug.Assert(obj!= null)

15.    每行代码应该经过白盒测试。
      Every line of code should be walked through in a搘hitebox?testing manner.

16.    仅捕获已经显式处理了的异常。
      Only catch exceptions for which you haveexplicit handling. 

17.    在抛出异常的catch语句中,总是抛出最初异常以保持最初错误的堆栈位置。
      In a catch statement that throws an exception,always throw the original exception to maintain stack location of originalerror.
     catch(Exception exception)
     {   
        MessageBox.Show(exception.Message);
        throw;  //Same as throwexception;
     }

18.    避免将错误代码作为方法的返回值。
      Avoid error code as methods return values. 

19.    避免定义自定义的异常类。
      Avoid defining customexception classes.

20.    定义自定义异常时:
      When defining custom exceptions:
      a) 从ApplicationException继承
        Derive the custom exception fromApplicationException.
      b) 提供自定义的序列化。
          Provide customserialization. 

21.    避免在一个程序集中有多个Main()方法。
      Avoid multiple Main()methods in a single assembly.

22.    仅对最需要的类型标记为public,其他的标记为internal。
      Make only the most necessary types  public,mark others as internal.

23.    避免采用friend程序集,因为这样增加了程序集间的耦合度。
      Avoid friend assemblies, as it increasesinter-assembly coupling.

24.    避免使用依赖于从特定位置运行的程序集的代码。
      Avoid code that relies on an assembly runningfrom a particular location.

25.    尽量减少应用程序集(客户端EXE程序集)的代码。采用类库而不要包含业务逻辑层代码。
      Minimize code inapplication assemblies (EXE client assemblies). Use class libraries instead tocontain business logic. 

26.    避免对枚举提供明确的值。
      Avoid providing explicitvalues for enums .
     //Correct 
     public enum Color
     {   
        Red,Green,Blue
     }
     //Avoid 
     public enum Color
     {   
        Red = 1,Green = 2,Blue = 3
     }

27.    避免对枚举指定类型。
      Avoid specifying a type for an enum.
     //Avoid 
     public enum Color : long
     {   
        Red,Green,Blue
     }

28.    if语句总是使用括号,即使它包含一句语句。
      Always use a curly bracescope in an if statement, even if  it conditions a single statement. 

29.    避免使用?:条件算符。
      Avoid using the trinary conditionaloperator. 

30.    避免在布尔条件语句中调用函数。赋值到局部变量并检查它们的值。
     Avoid function calls inBoolean conditional statements. Assign into local variables and check onthem: 
     bool IsEverythingOK()
     {...}
     //避免:
     //Avoid: 
     if(IsEverythingOK())
     {...}
     //采用:
     //Instead: 
     bool ok = IsEverythingOK();
     if(ok)
     {...}

31.    总是使用从0开始的数组。
     Always use zero-basedarrays. 

32.    总是使用一个for循环显式地初始化一个引用类型的数组。
     Always explicitly initialize an array of referencetypes using a for loop.
     public class MyClass
     {}
     MyClass[] array = new MyClass[100];
     for(int index = 0; index < array.Length; index++)
     {
        array[index] = new MyClass();
     }

33.    不用提供publicprotected成员变量,而是使用属性。
     Do not provide public orprotected member variables. Use properties instead. 

34.    避免使用new继承修饰符,而是使用override。
       Avoid using the new inheritance qualifier.Use override instead.  

35.    对非密封类总是将public和protected方法标记为virtual。
       Always mark  public and protected methods as  virtual in a non sealed class.

36.    除非涉及到互操作,永远不要用不安全的代码。
       Never use unsafe code unless when using interop. 

37.    避免显式类型转换。使用as算法防护性地转换类型。
       Avoid explicitcasting. Use the as operator to defensively cast to a type.
       Dog dog = new GermanShepherd();
       GermanShepherd shepherd = dog asGermanShepherd;
       if(shepherd != null)
       {...}

38.    类成员有委托时:
       With delegates as class members:
       a) 使用前将委托复制到局部变量,以避免并发冲突。
          Copy a delegate to alocal variable before publishing to avoid concurrency race condition. 
       b) 调用前始终检查委托是否为空。
          Always check a delegatefor null before invoking it.
       public class MySource
       {
          public eventEventHandler  MyEvent;
          public void FireEvent()
         {
            EventHandlertemp = MyEvent;
            if(temp !=null)
            {
              temp(this,EventArgs.Empty);
            }
         }
      }  

39.    不要提供public的事件成员变量,而是使用事件访问器。
       Do not providepublic event member variables. Use event accessors instead. 
       public class MySource
       {
          MyDelegate m_SomeEvent;
          public event MyDelegateSomeEvent
          {
             add
            {
               m_SomeEvent += value;
             }
             remove
            {
               m_SomeEvent -= value;
             }
          }
       }

40.    使用Programming .NET Components中定义的EventsHelper类安全地发布事件。
       Use the  EventsHelper class definedin Programming .NET Components to publish events defensively. 

41.    总是使用接口。
       Always use interfaces.
       a) 参见Programming .NET Components第一和第三章。
          See Chapters 1 and 3 in Programming .NET Components.

42.    类和接口中方法和属性的比例至少是2:1。
       Classes and interfaces should have atleast 2:1 ratio of methods to properties.

43.    避免使用一个成员的接口。
       Avoid interfaces with one member.

44.    努力使每个接口拥有3-5个成员。
       Strive to have 3-5 members per interface.

45.    每个接口不用超过20个成员。
       No more than 20 members per interface.
       a) 12可能是实际应用的极限了。
           12 is probably apractical limit. 

46.    避免将事件作为接口成员。
       Avoid events as interface members.

47.    避免使用抽象方法,而是使用接口代替。
       Avoid abstract methods, use interfacesinstead.

48.    在类层次中暴露接口。
       Expose interfaces on class hierarchies.
       a) 参见Programming .NET Components第三章。
          See Chapter 3 in Programming .NET Components.

49.    优先使用明确的接口实现。
       Prefer using explicit interfaceimplementation.
       a) 参见Programming .NET Components第三章。
          See Chapter 3 in Programming .NET Components.

50.    永远不要假设一种类型支持某个接口。防护性地检查是否支持该接口。
       Never assume a type supports an interface.Defensively query for that interface.
       SomeType obj1;
       IMyInterface obj2;
      
       /* Some code to initialize obj1, then: */
       obj2 = obj1 as IMyInterface;
       if(obj2 != null)
      {
        obj2.Method1();
       }
       else
      {
         //Handle error in expectedinterface 
      }  

51.    将呈现给用户的字符串永远不用硬编码,而是使用资源。
       Never hardcode strings that will bepresented to end users. Use resources instead.

52.    发布时可能修改的字符串永远不用硬编码,例如连接字符串。
       Never hardcode strings that might changebased on deployment such as connection strings. 

53.    构建一个长字符串时,使用StringBuilder,不要用string
       When building along string, use StringBuilder, not string.

54.    避免提供带结构的方法。
       Avoid providing methods onstructures. 
       a)  参数化的构造函数是鼓励使用的。
           Parameterized constructors are encouraged. 
       b)  可以重载算符。
            Can overloadoperators. 

55.    当提供静态成员变量时,总是提供一个静态构造函数。
       Always provide a static constructor whenproviding static member variables.

56.    只要可以用前期绑定就不要用后期绑定。
       Do not uselate-binding invocation when early-binding is possible.

57.    对应用程序进行日志和跟踪。
       Use application logging and tracing. 

58.    除非在switch语句中跳转,永远不要用goto语句。
       Never use gotounless in a switch statement fall-through.

59.    switch语句中总是使用default用于加断言。
       Always have adefault case in a switch statement that asserts .
       int number = SomeMethod();
       switch(number)
       {
          case 1:
            Trace.WriteLine("Case 1:");
             break;
          case 2:
            Trace.WriteLine("Case 2:");
             break;
          default:
            Debug.Assert(false);
             break;
       }

60.    除非在构造函数中调用另一个构造函数,否则不用使用this。
       Do not use the  this reference unlessinvoking another constructor from within a constructor.
       //Example of proper use of this
       public class MyClass
       {
          public MyClass(stringmessage)
          {}
          public MyClass() :this("hello")
          {}
       }

61.    除非为了解决调用基类构造函数时成员名的冲突,否则不要使用base访问基类的成员。
       Do not use the base word to access baseclass members unless you wish to resolve a conflict with a subclassesmember of the same name or when invoking a base class constructor. 
     //Example of proper use of 抌ase?
     public class Dog
     {
        public Dog(string name)
        {}
        virtual public void Bark(inthowLong)
        {}
     }
     public class GermanShepherd : Dog
     {
        public GermanShepherd(string name):base(name)
        {}
        override public void Bark(inthowLong) 
        {
          base.Bark(howLong);  
        }
     }

62.    根据Programming .NET Components第四章中的模板实现Dispose()和Finalize()方法。
       Implement  Dispose() and Finalize() methods based on the template  in Chapter 4 of Programming.NET Components. 

63.    使用泛型的代码中避免与System.Object进行类型转换,而是使用限制或as算符。
       Avoid casting to and from System.Object in code that uses generics. Use constraints or the as operatorinstead:
       class SomeClass
       {} 
        //避免 Avoid:
       class MyClass 
      {   
          void SomeMethod(Tt)   
         {
           object temp =t;      
           SomeClass obj =(SomeClass)temp;   
         }
       }
       //正确 Correct:
       class MyClass where T : SomeClass
       {   
          void SomeMethod(Tt)   
          {
            SomeClass obj = t;   
          }
       }

64.    泛型接口不要定义限制。接口层的限制通常能用强类型代替。
       Do not define constraints in genericinterfaces. Interface level-constraint can often be replaced bystrong-typing.
       public class Customer
       {...}
       //避免 Avoid:
       public interface IList where T :Customer 
       {...}
       //正确  Correct:
       public interface ICustomerList :IList 
       {...}

65.    不要在接口中定义与方法相关的限制。
       Do not define method-specific constraintsin interfaces.

66.    在数据结构中总是优先使用C#泛型。
       Always prefer using C# generics in datastructures. 

3.     项目设置和项目结构 Project Settings and Project Structure

1.        总是以4级警告建立项目(图略)。

Always buildyour project with warning level 4

2.        在发布版中将警告作为错误(注意这不是VS.NET的缺省设置)(图略)。
    Treat warning as errors in Releasebuild (note that this is not the default of VS.NET).     a) 虽然是可选的,本标准也推荐在调试版中将警告作为错误。 

Although it is optional, this standard recommend treating warningsas errors in debug builds as well.

3.        永远不要抑制特定的编译警告(图略)。

Never suppressspecific compiler warnings.

4.        总是在应用程序的配置文件中显式地说明支持的运行时版本。参见Programming .NET Components第五章。

Always explicitly state your supported runtime versions in theapplication configuration file. See Chapter 5 in Programming .NET Components.

5.        避免显式地自定义版本改向和绑定到CLR程序集。

   Avoid explicit custom version redirection and binding to CLR assemblies.

6.        避免显式的预编译定义(#define)。使用项目设置定义条件编译常量。 

   Avoid explicit preprocessor definitions (#define). Use the projectsettings for defining conditional compilation constants. 

7.        不要在AssemblyInfo.cs中放任何逻辑。

   Do not put any logic inside AssemblyInfo.cs.

8.        除了在AssemblyInfo.cs,不要在任何文件中放程序集属性。

   Do not put any assembly attributes in any file besides AssemblyInfo.cs.

9.        在AssemblyInfo.cs中提供所有字段,例如公司名称、描述、版权等。

Populate all fields in AssemblyInfo.cs such as company name, description, copyright notice.

10.    所有程序集应该使用相对路径引用。

   All assembly references should use relative path. 

11.     不允许在程序集中循环引用。

   Disallow cyclic references between assemblies. 

12.    避免多模块的程序集。

   Avoid multi-module assemblies.

13.    缺省总是以非检查的方式运行(为了性能考虑),但是对易于溢出或下溢的操作显式使用检查模式(图略)。

Always run code unchecked by default (for performance sake), butexplicitly in checked mode for overflow or underflow prone operations.

    int CalcPower(int number,int power)

    {

       int result = 1;

       for(int count = 1;count <= power;count++)

       {

          checked       

          {

              result *= number;

          }

       }

       return result;

    }

14.  避免使用Exception窗口(Debug|Exceptions)篡改异常处理。

    Avoid tampering with exception handling using the Exception window(Debug|Exceptions).

15.  努力对同一逻辑应用程序中(通常是一个解决方案)的所有程序集和客户端使用统一的版本号。

    Strive to use uniform version numbers on all assemblies and clients inthe same logical application (typically a solution).

16. Visual Studio.NET应用的配置文件命名为App.config,并将其包括在项目中。

    Name your Visual Studio.NET application configuration file asApp.config, and include it in the project.

17.  避免使用显式代码来排除方法(#if#endif),而是使用条件方法。

    Avoid explicit code exclusion of method calls  (#if...#endif). Use conditional methodsinstead.

    public class MyClass

    {

       [Conditional("MySpecialCondition")]

       public void MyMethod()

       {}

    }

18.  将VS.NET缺省的项目结构改为标准的布局,对项目文件夹和文件应用统一的结构。

    Modify VS.NET default project structure to your project standard layout,and apply uniform structure for project folders and files. 

19.  链接一个包含所有解决方案级信息的全局共享文件(图略)。

    Link all solution-wide information to a global shared file:

20.  制表符选用"插入空格",使用3个空格代替制表符。

    Insert spaces for tabs. Use 3 spaces instead of tabs。

    a) 在工具|选项|文本编辑器|C#|制表符中设置

       Tools|Options|Text Editor|C#|Tabs

21.  发布版中应该包含调试符号。

    Release build should contain debug symbols. 

22.  总是对程序集签名,包括客户端应用程序。

    Always sign your assemblies, including the client applications. 

23.  总是使用项目的SNK文件对互操作程序集签名(图略)。

    Always sign interop assemblies with the project's SNK file

4  Framework特别指导
   Framework Specific Guidelines 


4.1 数据访问 


    Data Access
1.  总是使用类型安全的数据集或者数据表。避免使用原始的ADO.NET
    Always use type-safe data sets  or data tables . Avoidraw ADO.NET.
2.  访问数据库时总是使用事务。
    Always use transactions when accessing a database. 
     a) 总是使用服务组件事务。
        Always use Enterprise Servicestransactions.
     b) 不要使用ADO.NET事务。
        Do not use ADO.NETtransactions. 
3.  总是将事务隔离级别设置为序列的。
    Always use transaction isolation level set to Serializable.
     a) 使用其它隔离级别需要管理层决定。
        Requires management decision to useanything else.
4.  不要使用服务器浏览器将数据库连接拖到Windows表单、ASP.NET表单或Web服务中。这样做耦合了界面层和数据层。
    Do not use the Server Explorer to drop connections onwindows forms, ASP.NET forms or web services. Doing so couples the presentationtier to the data tier. 
5.  避免使用SQL Server验证。
    Avoid SQL Server authentication. 
     a) 而是使用Windows验证。
        Use Windows authentication instead.
6.  将访问SQL Server的组件以调用该组件客户端不同的身份运行。
    Run components accessing SQL Server under separate identityfrom that of the calling client. 
7.  总是在高层用类型安全的类包装存储过程。仅在那个类中调用存储过程。
    Always wrap your stored procedures in a high level, typesafe class. Only that class invokes the stored procedures. 
8.  避免在存储过程中放任何逻辑。
    Avoid putting any logic inside a stored procedure.
     a) 如果存储过程中有IF,你可能犯了错误。
     If there is an IF inside a storedprocedure, you are doing something wrong.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值