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.

  • 請勿使用 "My" 或 "my" 作為變數名稱的一部分。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

  • 使用字串內插補點串連短字串,如下列程式碼所示。Use string interpolation to concatenate short strings, as shown in the following code.

    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. 如果您不是使用傳遞至事件的事件引數 (例如, 傳送者作為物件, e as EventArgs), 請使用寬鬆的委派, 並在您的程式碼中省略事件引數: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

使用 [嘗試 ...]使用例外狀況處理時的 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 Nothing而不是。Use 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)
    
  • NothingRaiseEvent呼叫方法之前, 請不要驗證事件是否為 (null)。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.

  • 使用內嵌運算式來包含值, 並從現有的值建立 XML, 而不是使用 API 呼叫Add , 例如方法: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. 例如, 如果您的查詢傳回客戶名稱和訂單識別碼, 請將其重新命名, 而不要在Name結果ID中將它們保留為和: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
    
  • 使用子句來明確定義聯結作業, 而不是Where使用子句來隱含定義聯結運算: JoinUse 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