C#命名規則和開發習慣

來源:互聯網
上載者:User
一、命名
 
1.用pascal規則來命名方法和類型.
public class TextBox
{
     public void DataBind() 
     {
     }
}
 
2.用camel規則來命名局部變數和方法的參數.
string userName;
public AddUser(string userId, byte[] password);
 
3.所有的成員變數前加首碼 m_
public class Database
{
     public string m_connectionString;
}
 
4.介面的名稱加首碼 I.
interface ICompare
{
     int compare();
}
 
5.自訂的屬性以Attribute結尾
public class AuthorAttribute : Attribute
{
}
 
6.自訂的異常以Exception結尾
public class AppException : Exception
{
}
 
7.方法的命名.一般將其命名為動賓短語.
ShowDialog()
CreateFile()
GetPath()
 
8.代碼的縮排.要用Tab,而不要用space.
 
9.局部變數的名稱要有意義.不要用x,y,z等等.
string userName
 
10.所有的成員變數聲明在類的頂端,用一個換行把它和方法分開.
 
11.用有意義的名字命名namespace,如:產品名、公司名.
 
12.建議局部變數在最接近使用它時再聲明.
 
13.使用某個控制項的值時,盡量命名局部變數.
 
14.把引用的系統的namespace和自訂或第三方的分開.
 
15.檔案名稱要能反應類的內容,最好是和類同名,一個檔案中一個類.
 
16.目錄結構中要反應出namespace的層次.
 
17.大括弧"{"要新起一行.
public class AuthorAttribute : Attribute
{
}
 
二、編碼習慣.
1.用C#預定義的類名,而不要用別名.
string userName;   而不是 System.String userName;
int number;            而不是 System.Int32;
 
2.一行不要超過80個字元.
 
3.盡量不要手工更改機器產生的程式碼,若必須更改,一定要改成和機器產生的程式碼風格一樣.
 
4.關鍵的語句(包括聲明關鍵的變數)必須要寫注釋.
 
5.文字常量和數字常量不要寫入程式碼,應該用常量類或枚舉代替.
 
6.不要用goto系列語句.
 
7.不要聲明public和protected的成員變數,應用property.
 
8.不要聲明public的event,應用事件訪問器.
public class Source
{
     private EventHandler m_NumberChangeEvent;
    
     public event EventHandler NumberChangeEvent
     {
         add
         {
              m_NumberChangeEvent += value;
         }
        
         remove
         {
              m_NumberChangeEvent -= value;
         }
     }
}
 
9.類型轉換的使用規則.
Animal animal = new Dog();
Dog dog = animal as Dog;
if (dog != null)
{
}
 
10.產生和構建一個長的字串時,一定要使用StringBuilder,而不用string.
 
11.始終使用"{  }"包含if下的語句,即使只有一條語句.
 
12.switch語句一定要有default來處理意外情況.
 
13.盡量不要使用三目運算子 ? : ,而要使用if語句.
 
14.盡量不用使用this引用,除非是要調用類中的另一個Constructor.
public class Person
{
     public Person(string name)
     {
     }
    
     public Person() : this("Jim"{
window.open('/images/wink.gif','_blank');
}" hspace="2" src="http://www.blogcn.com/images/wink.gif" onload="function anonymous()
{
if(this.width>screen.width/2)this.width=screen.width/2
}" vspace="2" border="0">
     {
     }
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.