Visual Basic 編碼慣例Visual Basic Coding Conventions

Microsoft 開發範例和文件,請遵循本主題中的指導方針。Microsoft develops samples and documentation that follow the guidelines in this topic. 如果您遵循相同的程式碼撰寫慣例,您可能會有下列好處:If you follow the same coding conventions, you may gain the following benefits:

  • 您的程式碼將會有一致的外觀,讓讀者可以更加專注於內容,而非版面配置。Your code will have a consistent look, so that readers can better focus on content, not layout.

  • 讀者了解您的程式碼更快速地因為它們會使先前的經驗為基礎的假設。Readers understand your code more quickly because they can make assumptions based on previous experience.

  • 您可以複製、 變更及更容易維護的程式碼。You can copy, change, and maintain the code more easily.

  • 您可以協助確保您的程式碼會示範 Visual Basic 的 「 最佳作法 」。You help ensure that your code demonstrates "best practices" for Visual Basic.

命名規範Naming Conventions

  • 命名方針的相關資訊,請參閱命名方針主題。For information about naming guidelines, see Naming Guidelines topic.

  • 請勿使用 「 我的 」 或 「 我的 」 做為變數名稱的一部分。Do not use "My" or "my" as part of a variable name. 這種作法會建立與產生混淆My物件。This practice creates confusion with the My objects.

  • 您沒有變更的自動產生的程式碼,使其符合指導方針中的物件名稱。You do not have to change the names of objects in auto-generated code to make them fit the guidelines.

版面配置慣例Layout Conventions

  • 插入空格 索引標籤,並使用四個空間縮排與智慧型縮排。Insert tabs as spaces, and use smart indenting with four-space indents.

  • 使用美化 (重新格式化) 的程式碼重新格式化程式碼編輯器中的程式碼。Use Pretty listing (reformatting) of code to reformat your code in the code editor. 如需詳細資訊,請參閱選項、 文字編輯器、 基本 (Visual Basic)For more information, see Options, Text Editor, Basic (Visual Basic).

  • 使用每行只能有一個陳述式。Use only one statement per line. 請勿使用 Visual Basic 行分隔符號字元 (:)。Don't use the Visual Basic line separator character (:).

  • 請避免使用明確的行接續字元""改為隱含行接續符號,只要該語言允許它。Avoid using the explicit line continuation character "" in favor of implicit line continuation wherever the language allows it.

  • 使用每行只有一個宣告。Use only one declaration per line.

  • 如果美化 (重新格式化) 的程式碼不接續線格式自動、 手動縮排接續行一個定位停駐點。If Pretty listing (reformatting) of code doesn't format continuation lines automatically, manually indent continuation lines one tab stop. 不過,一律靠左對齊清單項目。However, always left-align items in a list.

    a As Integer,  
    b As Integer  
    
  • 加入方法和屬性定義之間的至少一個空白行。Add at least one blank line between method and property definitions.

註解慣例Commenting Conventions

  • 將註解放在程式碼行結尾處而不是個別行上。Put comments on a separate line instead of at the end of a line of code.

  • 開始註解文字以大寫的字母,並以句號結束註解文字。Start comment text with an uppercase letter, and end comment text with a period.

  • 插入註解分隔符號 (') 與註解文字之間的一個空格。Insert one space between the comment delimiter (') and the comment text.

    ' Here is a comment.
    
  • 請勿用格式化的星號區塊註解。Do not surround comments with formatted blocks of asterisks.

程式結構Program Structure

  • 當您使用Main方法,使用預設建構新的主控台應用程式,並使用My命令列引數。When you use the Main method, use the default construct for new console applications, and use My for command-line arguments.

    Sub Main()
      For Each argument As String In My.Application.CommandLineArgs
        ' Add code here to use the string variable.
      Next
    End Sub
    

語言指導方針Language Guidelines

String 資料類型String Data Type

  • 若要串連的字串,使用連字號 (&)。To concatenate strings, use an ampersand (&).

    MsgBox("hello" & vbCrLf & "goodbye")
    
  • 若要將附加在迴圈中的字串,請使用StringBuilder物件。To append strings in loops, use the StringBuilder object.

    Dim longString As New System.Text.StringBuilder
    For count As Integer = 1 To 1000
      longString.Append(count)
    Next
    

寬鬆的委派事件處理常式中Relaxed Delegates in Event Handlers

未明確限定 (物件和 EventArgs) 的引數加入事件處理常式。Do not explicitly qualify the arguments (Object and EventArgs) to event handlers. 如果您未使用的事件引數會傳遞至事件 (例如,傳送者為物件,為 EventArgs e),使用鬆散的委派和事件引數,在程式碼中會省略:If you are not using the event arguments that are passed to an event (for example, sender as Object, e as EventArgs), use relaxed delegates, and leave out the event arguments in your code:

Public Sub Form1_Load() Handles Form1.Load
End Sub

不帶正負號的資料類型Unsigned Data Type

  • 使用Integer而不是不帶正負號的類型,除非它們是必要。Use Integer rather than unsigned types, except where they are necessary.

陣列Arrays

  • 當您初始化陣列宣告行上的時,請使用簡短的語法。Use the short syntax when you initialize arrays on the declaration line. 例如,使用下列語法。For example, use the following syntax.

    Dim letters1 As String() = {"a", "b", "c"}
    

    請勿使用下列語法。Do not use the following syntax.

    Dim letters2() As String = New String() {"a", "b", "c"}
    
  • 型別,而非變數,請將陣列指示項。Put the array designator on the type, not on the variable. 例如,使用下列語法:For example, use the following syntax:

    Dim letters4 As String() = {"a", "b", "c"}
    

    請勿使用下列語法:Do not use the following syntax:

    Dim letters3() As String = {"a", "b", "c"}
    
  • 如果您宣告並初始化陣列的基本資料型別,請使用 {} 語法。Use the { } syntax when you declare and initialize arrays of basic data types. 例如,使用下列語法:For example, use the following syntax:

    Dim letters5 As String() = {"a", "b", "c"}
    

    請勿使用下列語法:Do not use the following syntax:

    Dim letters6(2) As String
    letters6(0) = "a"
    letters6(1) = "b"
    letters6(2) = "c"
    

使用 With 關鍵字Use the With Keyword

當您進行一系列的一個物件的呼叫時,請考慮使用With關鍵字:When you make a series of calls to one object, consider using the With keyword:

With orderLog
  .Log = "Application"
  .Source = "Application Name"
  .MachineName = "Computer Name"
End With

使用 Try...Catch 和 Using 陳述式時,您可以使用例外狀況處理Use the Try...Catch and Using Statements when you use Exception Handling

請勿使用On Error GotoDo not use On Error Goto.

使用 IsNot 關鍵字Use the IsNot Keyword

使用IsNot關鍵字取代Not...Is NothingUse the IsNot keyword instead of Not...Is Nothing.

New 關鍵字New Keyword

  • 使用簡短的具現化。Use short instantiation. 例如,使用下列語法:For example, use the following syntax:

    Dim employees As New List(Of String)
    

    前一行相當於這個:The preceding line is equivalent to this:

    Dim employees2 As List(Of String) = New List(Of String)
    
  • 為新的物件,而不是無參數建構函式中使用物件初始設定式:Use object initializers for new objects instead of the parameterless constructor:

    Dim orderLog As New EventLog With { 
        .Log = "Application", 
        .Source = "Application Name", 
        .MachineName = "Computer Name"}
    

事件處理Event Handling

  • 使用Handles而不是AddHandler:Use Handles rather than AddHandler:

    Private Sub ToolStripMenuItem1_Click() Handles ToolStripMenuItem1.Click
    End Sub
    
  • 使用AddressOf,並執行不具現化委派明確:Use AddressOf, and do not instantiate the delegate explicitly:

    Dim closeItem As New ToolStripMenuItem( 
        "Close", Nothing, AddressOf ToolStripMenuItem1_Click)
    Me.MainMenuStrip.Items.Add(closeItem)
    
  • 當您定義事件時,使用簡短的語法,並讓編譯器定義委派:When you define an event, use the short syntax, and let the compiler define the delegate:

    Public Event SampleEvent As EventHandler(Of SampleEventArgs)
    ' or
    Public Event SampleEvent(ByVal source As Object, 
                              ByVal e As SampleEventArgs)
    
  • 無法驗證事件是否Nothing(null) 才能呼叫RaiseEvent方法。Do not verify whether an event is Nothing (null) before you call the RaiseEvent method. RaiseEvent 檢查是否有Nothing引發事件之前。RaiseEvent checks for Nothing before it raises the event.

使用共用的成員Using Shared Members

呼叫Shared使用類別名稱,不是從執行個體變數成員。Call Shared members by using the class name, not from an instance variable.

使用 XML 常值Use XML Literals

XML 常值簡化最常見的工作會遇到當您使用 XML (例如載入、 查詢和轉換)。XML literals simplify the most common tasks that you encounter when you work with XML (for example, load, query, and transform). 當您使用 XML 進行開發時,請遵循這些指導方針:When you develop with XML, follow these guidelines:

  • 您可以使用 XML 常值來建立 XML 文件和片段,而不是直接呼叫 XML Api。Use XML literals to create XML documents and fragments instead of calling XML APIs directly.

  • 匯入 XML 命名空間,在檔案或專案層級,若要善用 XML 常值的效能最佳化。Import XML namespaces at the file or project level to take advantage of the performance optimizations for XML literals.

  • 您可以使用 XML 軸屬性來存取 XML 文件中元素和屬性。Use the XML axis properties to access elements and attributes in an XML document.

  • 使用內嵌的運算式包含值,並建立從現有的值,而不是使用 API 呼叫,例如 XMLAdd方法:Use embedded expressions to include values and to create XML from existing values instead of using API calls such as the Add method:

    Private Function GetHtmlDocument( 
        ByVal items As IEnumerable(Of XElement)) As String
    
      Dim htmlDoc = <html>
                      <body>
                        <table border="0" cellspacing="2">
                          <%= 
                            From item In items 
                            Select <tr>
                                     <td style="width:480">
                                       <%= item.<title>.Value %>
                                     </td>
                                     <td><%= item.<pubDate>.Value %></td>
                                   </tr> 
                          %>
                        </table>
                      </body>
                    </html>
    
      Return htmlDoc.ToString()
    End Function
    

LINQ 查詢LINQ Queries

  • 使用有意義的名稱,請為查詢變數:Use meaningful names for query variables:

    Dim seattleCustomers = From cust In customers 
                           Where cust.City = "Seattle"
    
  • 提供名稱的項目查詢中,以確定,匿名類型的屬性名稱都正確大寫使用 Pascal 大小寫:Provide names for elements in a query to make sure that property names of anonymous types are correctly capitalized using Pascal casing:

    Dim customerOrders = From customer In customers 
                         Join order In orders 
                           On customer.CustomerID Equals order.CustomerID 
                         Select Customer = customer, Order = order
    
  • 當結果中的屬性名稱可能會造成混淆時,請重新命名屬性。Rename properties when the property names in the result would be ambiguous. 例如,如果您的查詢會傳回客戶名稱和訂單 ID,將其重新命名而非讓它們當做NameID結果:For example, if your query returns a customer name and an order ID, rename them instead of leaving them as Name and ID in the result:

    Dim customerOrders2 = From cust In customers 
                          Join ord In orders
                            On cust.CustomerID Equals ord.CustomerID 
                          Select CustomerName = cust.Name, 
                                 OrderID = ord.ID
    
  • 使用類型推斷的查詢變數和範圍變數宣告中:Use type inference in the declaration of query variables and range variables:

    Dim customerList = From cust In customers
    
  • 下對齊查詢子句From陳述式:Align query clauses under the From statement:

    Dim newyorkCustomers = From cust In customers 
                           Where cust.City = "New York" 
                           Select cust.LastName, cust.CompanyName
    
  • 使用Where子句之前其他查詢子句,以便之後的查詢子句對篩選的資料集:Use Where clauses before other query clauses so that later query clauses operate on the filtered set of data:

    Dim newyorkCustomers2 = From cust In customers 
                            Where cust.City = "New York" 
                            Order By cust.LastName
    
  • 使用Join子句來明確定義的聯結作業,而不使用Where子句來隱含定義為聯結作業:Use the Join clause to explicitly define a join operation instead of using the Where clause to implicitly define a join operation:

    Dim customerList2 = From cust In customers 
                        Join order In orders 
                          On cust.CustomerID Equals order.CustomerID 
                        Select cust, order
    

另請參閱See Also

安全程式碼撰寫方針Secure Coding Guidelines