1.  避免将多个类放在一个文件里面。 2.  一个文件应该只有一个命名空间,避免将多个命名空间放在同一个文件里面。3.  一个文件最好不要超过500行的代码(不包括机器产生的代码)。4.  一个方法的代码长度最好不要超过25行。5.  避免方法中有超过5个参数的情况。使用结构来传递多个参数。6.  每行代码不要超过80个字符。7.  不要手工的修改机器产生的代码。a)  如果需要编辑机器产生的代码,编辑格式和风格要符合该编码标准。b)  Use partial classes whenever possible to factor out the maintained portions. 8.  避免利用注释解释显而易见的代码。a)  代码应该可以自解释。好的代码由可读的变量和方法命名因此不需要注释。9.  Document only operational assumptions, algorithm insights and so on.   10.  避免使用方法级的文档。a)  使用扩展的API文档说明之。b)  只有在该方法需要被其他的开发者使用的时候才使用方法级的注释。(在C#中就是///)11.  不要硬编码数字的值,总是使用构造函数设定其值。12.  只有是自然结构才能直接使用const,比如一个星期的天数。13.  避免在只读的变量上使用const。如果想实现只读,可以直接使用readonly。public class MyClass {    public readonly int Number;    public MyClass(int  someValue)    {       Number = someValue;    }    public  const int  DaysInWeek = 7; } 14.  每个假设必须使用Assert检查a)  平均每15行要有一次检查(Assert)using System.Diagnostics;  object GetObject() {…}  object obj = GetObject(); Debug.Assert(obj != null); 15.  代码的每一行都应该通过白盒方式的测试。16.  只抛出已经显示处理的异常。17.  在捕获(catch)语句的抛出异常子句中(throw),总是抛出原始异常维护原始错误的堆栈分配。catch(Exception exception) {       MessageBox.Show(exception.Message);    throw ;  //和throw exception一样。 } 18.  避免方法的返回值是错误代码。19.  尽量避免定义自定义异常类。20.  当需要定义自定义的异常时:a)  自定义异常要继承于ApplicationException。b)  提供自定义的序列化功能。21.  避免在单个程序集里使用多个Main方法。22.  只对外公布必要的操作,其他的则为internal。23.  Avoid friend assemblies, as it increases inter-assembly coupling.24.  Avoid code that relies on an assembly running from a particular location. 25.  使应用程序集尽量为最小化代码(EXE客户程序)。使用类库来替换包含的商务逻辑。26.  避免给枚举变量提供显式的值。//正确方法  public enum Color {       Red,Green,Blue } //避免public enum Color {       Red = 1,Green =  2,Blue = 3 } 27.  避免指定特殊类型的枚举变量。//避免  public enum Color  : long {       Red,Green,Blue } 28.  即使if语句只有一句,也要将if语句的内容用大括号扩起来。29.  避免使用trinary条件操作符。30.  避免在条件语句中调用返回bool值的函数。可以使用局部变量并检查这些局部变量。bool IsEverythingOK() {…} //避免 if (IsEverythingOK ()) {…} //替换方案  bool ok = IsEverythingOK(); if (ok) {…} 31.  总是使用基于0开始的数组。32.  在循环中总是显式的初始化引用类型的数组。public class MyClass {} MyClass[] array = new  MyClass[100]; for(int index = 0; index < array.Length;  index++) {    array[index] = new  MyClass(); } 33.  不要提供public 和 protected的成员变量,使用属性代替他们。34.  避免在继承中使用new而使用override替换。35.  在不是sealed的类中总是将public 和 protected的方法标记成virtual的。36.  除非使用interop(COM+ 或其他的dll)代码否则不要使用不安全的代码(unsafe code)。37.  避免显示的转换,使用as操作符进行兼容类型的转换。Dog dog = new GermanShepherd(); GermanShepherd shepherd = dog  as  GermanShepherd; if (shepherd != null ) {…} 38.  当类成员包括委托的时候a)  Copy a delegate to a local variable before publishing to avoid concurrency race condition.  b)  在调用委托之前一定要检查它是否为nullpublic class MySource {    public event EventHandler  MyEvent;    public void FireEvent()    {       EventHandler temp = MyEvent;       if(temp != null )       {          temp(this,EventArgs.Empty);       }    } }   39.  不要提供公共的事件成员变量,使用事件访问器替换这些变量。public class MySource {    MyDelegate m_SomeEvent ;    public event MyDelegate SomeEvent    {       add       {          m_SomeEvent += value;       }       remove       {          m_SomeEvent -= value;       }    } } 40.  使用一个事件帮助类来公布事件的定义。 41.  总是使用接口。42.  类和接口中的方法和属性至少为2:1的比例。43.  避免一个接口中只有一个成员。44.  尽量使每个接口中包含3-5个成员。45.  接口中的成员不应该超过20个。a)  实际情况可能限制为12个 46.  避免接口成员中包含事件。47.  避免使用抽象方法而使用接口替换。48.  在类层次中显示接口。49.  推荐使用显式的接口实现。50.  从不假设一个类型兼容一个接口。Defensively query for that interface.SomeType obj1; IMyInterface obj2; 
/* 假设已有代码初始化过obj1,接下来 */ obj2 = obj1 as IMyInterface; if (obj2 != null) {    obj2.Method1(); } else {    //处理错误 }   51.  表现给最终用户的字符串不要使用硬编码而要使用资源文件替换之。52.  不要硬编码可能更改的基于配置的字符串,比如连接字符串。53.  当需要构建长的字符串的时候,使用StringBuilder不要使用string54.  避免在结构里面提供方法。a)  建议使用参数化构造函数b)  可以重裁操作符55.  总是要给静态变量提供静态构造函数。56.  能使用早期绑定就不要使用后期绑定。57.  使用应用程序的日志和跟踪。58.  除非在不完全的switch语句中否则不要使用goto语句。59.  在switch语句中总是要有default子句来显示信息(Assert)。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指针。// 正确使用this的例子 public class MyClass {    public MyClass(string message )    {}    public MyClass()  : this("hello")    {} } 61.  除非你想重写子类中存在名称冲突的成员或者调用基类的构造函数否则不要使用base来访问基类的成员。// 正确使用base的例子public class Dog {    public Dog(string name)    {}    virtual public void Bark( int howLong)    {} } public class GermanShepherd : Dog {    public GermanShe pherd(string name): base (name)    {}    override public void Bark(int  howLong)     {       base .Bark(howLong);      } } 62.  基于模板的时候要实现Dispose()和Finalize()两个方法。63.  通常情况下避免有从System.Object转换来和由System.Object转换去的代码,而使用强制转换或者as操作符替换。class SomeClass {} //避免: class MyClass<T>  {       void SomeMethod(T t)       {       object temp = t;             SomeClass obj = (SomeClass)temp;        } } // 正确: class MyClass<T> where T : SomeClass {       void SomeMethod(T t)       {       SomeClass obj = t;       } } 64.  在一般情况下不要定影有限制符的接口。接口的限制级别通常可以用强类型来替换之。public class Customer {…} //避免:public interface IList<T> where T : Customer  {…} //正确:public interface ICustomerList : IList<Customer>  {…} 65.  不确定在接口内的具体方法的限制条件。66.  总是选择使用C#内置(一般的generics)的数据结构。 http://www.cnblogs.com/zhangronghua/archive/2006/12/20/598386.html

解决方案 »

  1.   

    这是比较传统的规范,.net代码分析器比这个全,
    但在今天有不少已经是是不大合适的,所以微软对代码分析器的分析条件都是可选择的,
    随便几个例子,针对楼主的第五条:
    "5.  避免方法中有超过5个参数的情况。使用结构来传递多个参数。"为了避免使用参数,你要设计一个结构或者类,貌似OO的做法实际是反OO的
    1.那么类的设计就变成了累的设计,而且别人看到这些类根本不知道是干什么的;
    2.如果方法的参数发生了变化,则需要重新设计类,
    这就是不良耦合(除非你有自动化的方式替换与之相关的类),这就好比计算机的
    主板和内存是良好的耦合,更换或增加内存不用变更主板;而硬件和操作系统
    属于不良耦合,但操作系统(例如XP)能够识别不少硬件,并自动的做相应的驱动调整,
    这又降低了硬件与软件的耦合度;
    3.虽然方法的参数越多,调用层的耦合度越大,但是实现调用的自动化相对容易得多,
    并且调用层不需要借助文档就能一眼看出方法需要什么影响了什么;
      

  2.   

    总之,利用面向对象的理论(而不是结论),照搬结论不一定能提到质量或效率,可能适得其反.
    这里班门弄斧说一说自己的心得:
    1.面向对象可以是面向对象特征(属性),也可以是面向服务(方法);
    服务要比特征更加稳定;
    2.降低耦合(隔离),我认为耦合分为代码耦合和工序耦合,
    通常构建了一大堆对象,结果并没有感到轻松,往往代码弱耦合了,工序强耦合了,
    例如方法的参数设计成了类,参数是减少了(调用接口也变得稳定了,这就是代码耦合降低了),
    可是如果不借助文档,程序员很难弄清方法需要什么又改变了什么(工序耦合增加了),
    开发项目时时这种情况,后期维护就更不用说了,
    应该使用代码自动化降低代码耦合,增加自动化工序降低手工工序减少工序耦合;
    3.面向修改封闭,面向扩展开放
    设计应该尽可能以不修改原有代码的方式满足需求变更,
    通过代码自动化以替换方式代替修改方式改进项目;
    4.MVC三层开发体系中:
    从M层驱动是最差的驱动方式,
    从C层驱动是最佳驱动方式,这跟前面的第一点是相辅相成的.
    有不同意见欢迎拍砖
      

  3.   

    22.  只对外公布必要的操作,其他的则为internal。 //其它的应该为private(个人感觉)
      

  4.   

    我离楼主说的还很遥远。
    学习ing.............
      

  5.   

    楼主很厉害,写了这么多注意事项,好多都没注意过…………
    个人也比较赞同 microtry 的说法
      

  6.   

    在微软网站下载的吧,C# Coding Standards,多谢LZ翻译,呵呵。
      

  7.   

    1. Introduction 3
    1.1 Purpose 3
    1.2 Scope 3
    1.3 Document Conventions 3
    1.4 Feedback 3
    2. C# Golden Rules 4
    3. Formatting 5
    3.1 Class Layout 5
    3.2 Indicating Scope 5
    3.3 Indentation & Braces 6
    3.4 White space 6
    3.5 Long lines of code 7
    4. Commenting 8
    4.1 Intellisense Comments 8
    4.2 End-Of-Line Comments 8
    4.3 Single Line Comments 8
    4.4 // TODO: Comments 8
    4.5 C-Style Comments 8
    5. Capitalization & Naming 9
    5.1 Capitalization 9
    5.2 Naming 9
    6. Programming 10
    6.1 Namespaces 10
    6.2 Classes & Structures 10
    6.3 Interfaces 10
    6.4 Constants 11
    6.5 Enumerations 11
    6.6 Variables, Fields & Parameters 11
    6.7 Properties 12
    6.8 Methods 13
    6.9 Event Handlers 13
    6.10 Error Handling 13
    Appendix A. Naming Parts & Pairs 15
    A.1 Common Adjective Pairs   A.2 Common Property Prefixes 15
    A.3 Common Verb Pairs 15
    A.4 Common Qualifiers Suffixes 15
    Appendix B. References 16
    Revision History 17
      

  8.   

    Introduction
    1.1 Purpose
    The purpose of this document is to provide coding style standards for the development of source code written in C#. Adhering to a coding style standard is an industry proven best-practice for making team development more efficient and application maintenance more cost-effective. While not comprehensive, these guidelines represent the minimum level of standardization expected in the source code of projects written in C#. 
    1.2 Scope
    This document provides guidance on the formatting, commenting, naming, and programming style of C# source code and is applicable to component libraries. web services, web sites, and rich client applications.
    1.3 Document Conventions
    Example code is shown using the Code font and shows syntax as it would be color coded in Visual Studio’s code editor.
    1.4 Feedback
    Feedback on these guidelines is highly encouraged. Please send any questions or comments to your application architect.
      

  9.   

    2. C# Golden Rules
    The following guidelines are applicable to all aspects C# development:
    o Follow the style of existing code. Strive to maintain consistency within the code base of an application. If further guidance is needed, look to these guidelines and the .NET framework for clarification and examples.
    o Make code as simple and readable as possible. Assume that someone else will be reading your code.
    o Prefer small cohesive classes and methods to large monolithic ones. 
    o Use a separate file for each class, struct, interface, enumeration, and delegate with the exception of those nested within another class.
    o Write the comments first. When writing a new method, write the comments for each step the method will perform before coding a single statement. These comments will become the headings for each block of code that gets implemented.
    o Use liberal, meaningful comments within each class, method, and block of code to document the purpose of the code.
    o Mark incomplete code with // TODO: comments. When working with many classes at once, it can be very easy to lose a train of thought.
    o Never hard code “magic” values into code (strings or numbers). Instead, define constants, static read-only variables, and enumerations or read the values from configuration or resource files.
    o Prefer while and foreach over other available looping constructs when applicable. They are logically simpler and easier to code and debug.
    o Use the StringBuilder class and it’s Append(), AppendFormat(), and ToString() methods instead of the string concatenation operator (+=) for much more efficient use of memory.
    o Be sure Dispose() gets called on IDisposable objects that you create locally within a method. This is most commonly done in the finally clause of a try block. It’s done automatically when a using statement is used.
    o Never present debug information to yourself or the end user via the UI (e.g. MessageBox). Use tracing and logging facilities to output debug information.
    o Gaps and exceptions to these guidelines should be discussed and resolved with your application architect.3. Formatting
    3.1 Class Layout
    Classes should be organized into regions within an application using a layout determined by your application architect. These may be based on accessibility, type, or functionality. Consult your architect for the layout strategy used in your application.
    Example:
    // Class layout based on accessibility
    class Purchasing
    {
    #region Main

    #region Public

    #region Internal #region Protected #region Private #region Extern #region Designer Generated Code
    }
    Guidelines:
    o Use the same layout consistently in all classes in an application.
    o Omit regions if their associated class elements are not needed.
    o The Designer Generated Code region created by Visual Studio’s Visual Designer should never be modified by hand. It should contain only code generated by the designer.
      

  10.   

    如果再和Java编码规范一起放的话。呵呵。更好~~~~
      

  11.   

    传到CSDN上去了,大家去下载,呵呵:
    http://download.csdn.net/source/1035170
      

  12.   

    19.  尽量避免定义自定义异常类。 
    20.  当需要定义自定义的异常时: 
    a)  自定义异常要继承于ApplicationException。 微软是建议集成Exception类,自定义异常还是很有用的。系统的异常类只能记录最后一次抛出异常的方法和跟踪信息,而自定义的话可以重写,包含整个过程的Trace。
    ---------------------
    51.  表现给最终用户的字符串不要使用硬编码而要使用资源文件替换之。 这个最好用XML吧,资源文件修改了也要重新编译。