C#編碼規範和編程好習慣(2)

花括弧需獨立一行,而不象if, for 等可以跟括號在同一行。
好:
if ( ... )  

{   

// Do something  

}
不好:
if ( ... ) {   // Do something  }
在每個運算符和括號的前後都空一格。
好:
 if ( showResult == true )  

{  

for ( int i = 0; i < 10; i++ )  

{    
//   

    }  

}
不好:
  if(showResult==true)
  {
   for(int i= 0;i<10;i++)
   {
    //
   }
  }
良好的編程習慣
遵從以下良好的習慣以寫出好程序
bool SayHello ( string name ) 

{  

string fullMessage = "Hello " + name;  DateTime currentTime = DateTime.Now;   

string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();    

MessageBox.Show ( message );    

if ( ... ) 

{   

// Do something   // ...      return false;  

    }    return true

}    
避免使用大文件。如果一個文件裏的代碼超過300~400行,必須考慮將代碼分開到不同類中。
避免寫太長的方法。一個典型的方法代碼在1~25行之間。如果一個方法發代碼超過25行,應該考慮將其分解爲不同的方法。
方法名需能看出它作什麼。別使用會引起誤解的名字。如果名字一目瞭然,就無需用文檔來解釋方法的功能了。
好:
void SavePhoneNumber ( string phoneNumber ) 

{  

// Save the phone number. 

}
不好:
// This method will save the phone number. 

void SaveData ( string phoneNumber ) 

{  

// Save the phone number. 

}
一個方法只完成一個任務。不要把多個任務組合到一個方法中,即使那些任務非常小。
好:
 // Save the address.
 SaveAddress (  address );
 
 // Send an email to the supervisor to inform that the address is updated.
 SendEmail ( address, email );  
 
 void SaveAddress ( string address )
 {
  // Save the address.
  // ...
 }
 
 void SendEmail ( string address, string email )
 {
  // Send an email to inform the supervisor that the address is changed.
  // ...
 }
不好:
 // Save address and send an email to the supervisor to inform that the address is updated.
 SaveAddress ( address, email );
 void SaveAddress ( string address, string email )
 {
  // Job 1.
  // Save the address.
  // ...
  // Job 2.
  // Send an email to inform the supervisor that the address is changed.
  // ...
 }
使用C# 或 VB.NET的特有類型,而不是System命名空間中定義的別名類型。
好:
int age; 

string name; 

object contactInfo;
不好:
Int16 age; String name; Object contactInfo;
別在程序中使用固定數值,用常量代替。
別用字符串常數。用資源文件。
避免使用很多成員變量。聲明局部變量,並傳遞給方法。不要在方法間共享成員變量。如果在幾個方法間共享一個成員變量,那就很難知道是哪個方法在什麼時候修改了它的值。
必要時使用enum 。別用數字或字符串來指示離散值。
好:
enum MailType 

{  

Html,  PlainText,  Attachment 



void SendMail (string message, MailType mailType) 

{  

switch ( mailType )  

{   

case MailType.Html:    

// Do something    

        break;  

case MailType.PlainText:    

// Do something    

        break;   

case MailType.Attachment:    

// Do something    

        break;   

default:    

// Do something    

        break



}
不好:
void SendMail (string message, string mailType) 

{  

switch ( mailType )  

{   

case "Html":    

// Do something    

        break;   

case "PlainText":    

// Do something    

        break;   

case "Attachment":     

// Do something    

        break;   

default:    

// Do something   

         break;  



}
別把成員變量聲明爲 public 或 protected。都聲明爲 private 而使用 public/protected 的Properties。
不在代碼中使用具體的路徑和驅動器名。 使用相對路徑,並使路徑可編程。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章