65.9K
CodeProject 正在变化。 阅读更多。
Home

.NET 编码最佳实践

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.58/5 (27投票s)

2009 年 12 月 22 日

CPOL

2分钟阅读

viewsIcon

51536

.NET 编码最佳实践 - Vinayak 的经验法则不要硬编码字符串/数字。 而是使用常量,如下所示。不良实践 int Count; Count = 100; if( Count == 0 ) { // 执行某些操作… }良好实践 int Count; Count = 100; private...

.NET 编码最佳实践 - Vinayak 的经验法则
  1. 不要硬编码字符串/数字。 而是使用常量,如下所示。 不良实践
     int Count;
     Count = 100;
     if(  Count  ==  0 )
     {
      // DO something…
     }
    
    良好实践
     int Count;
     Count = 100;
     private static const int ZERO  =  0;
     if(  Count  ==  ZERO )
      {
        // DO something…
      }
    
  2. 对于字符串比较 - 使用 String.Empty 代替 “”
  3. 默认情况下,将成员变量的作用域设置为“private”,根据需要将其扩展到 protected、public 或 internal。
    1. 默认使作用域为 private 的另一个优势是,在 XMLSerilaization 期间,它默认会序列化所有公共成员。
  4. 当需要在循环内操作字符串时,使用 StringBuilder 代替 string,如下所示。 不良实践
     String  temp = String.Empty;
     for( int I = 0 ; I<= 100; i++)
     {
       Temp += i.ToString();
     }
    
    良好实践
      StringBuilder sb = new StringBuilder();
      for ( int I = 0 ; I<= 100; i++)
       {
         sb.Append(i.ToString());
        }
    
  5. 对于简单操作,优先使用数组而不是集合。
  6. 优先使用泛型集合而不是 ArrayList
  7. 优先使用泛型字典而不是 HashTable *。
  8. 对于字符串操作和存储,优先使用 StringCollections 和 StringDictionaries。
  9. 使用适当的数据类型。 例如:如果您想检查任何状态,请优先使用 bool 而不是 int。 不良实践
      int Check = 0;
      if(Check == 0)
       {
         // DO something
        }
    
    良好实践
      bool Check = false;
      if(!Check)
        {
          // DO something
        }
    
  10. 使用“as”运算符进行类型转换,并在使用结果值之前检查是否为 null。
    class A
     {
     }
    
    class B : A
     {
     }
    
    B objB = new B();
    A objA1  = (A) objB;
    A objA 2 = objB as A;
    
    if( objA2 != null)
    {
     //Do something
    }
    
  11. 对于 WCF 代理创建,使用 using 语句
     using(Cerate the proxy)
      {
        //Do the required operation
       }
    
  12. 遵循“晚获取,早释放”规则,对于昂贵的资源,例如连接、文件等。 例如:如果您想对任何数据操作使用 SqlConnection 对象,请在方法级别而不是类级别创建实例。
     class MyData
      {
          public MyData()
            {
            }
          public List GetAllCustomer()
            {
            using(SqlConnection objConnection = new SqlConnection(“Connection string”))
              {
    	        //Do the operation and get the required data..
              }
            }   
     }
    
    如果您想在类级别创建 SqlConnection 实例,请确保为该类实现 IDisposable,并在 Dispose(); 中清理 SqlConnection 实例。
     class MyData : IDisposable
      {
         SqlConnection objConnection = default(SqlCOnnection);
         public MyData(){
           objConnection = new SqlCOnnection(“Connection string”);
         }
         public List GetAllCustomer(){
           // By using objConnection get the required data
         }
         public void Dispose(){
          // Do the cleanup of SqlCOnnection
          if( objConnection != null ){
             if( objConnection.State == ConnectionState.Open){
     	    objConnection.Close();
             }
          }
        }
     }
    
  13. 如果您不希望任何人扩展您的类功能,请将其设为“sealed”,以获得内联和编译时优势
  14. 避免为每个类声明“析构函数”。 这会增加类的生命周期,不必要地使其存活时间过长
  15. 优先使用线程池而不是手动线程。
  16. 不要在循环中调用任何方法。 例如:不良实践
    for( int i = 0; i<= 100; i++)
    {
    	Calculate(i);
    }
    
    良好实践
    for( int i = 0; i<= 100; i++)
    {
      //Inline the body of Calculate.
    }
    
  17. 不要在循环内处理异常,而是在 try/catch 中处理循环逻辑。 例如:不良实践
    for(int i = 0 ; i<= 100; i++){
       try{
       }
       catch(Exception ex){
          throw ex;
       }
    }
    
    良好实践
      try{
        for(int i = 0 ; i<= 100; i++){
        }
      }
      catch(Exception ex){
       throw ex;
      }
    
  18. 不要使用 Exception 处理应用程序逻辑。 例如:不良实践
     try{
       int  x,y,z;
       x = 0;
       y = 10;
       z = y/x;
      }
     catch(DevideByZeroException ex){
       throw ex;
     }
    
    良好实践
      private static const int ZERO  =  0; 
      try{
        int x,y,z;
        x = 0;
        y = 10;
        if( x != ZERO){
          z = y/x;
        }
       }
      catch(Exception ex){
       }
    
  19. 优先使用 for/while 循环而不是 foreach
  20. 对于层之间的通信,优先使用数据传输对象而不是 DataSet/DataTables。
希望这能帮助大家提高代码质量!! 祝您编程愉快 问候,-Vinayak
© . All rights reserved.