逐步解說:建立程式碼片段Walkthrough: Create a code snippet

只需要幾個步驟就能建立程式碼片段。You can create a code snippet with only a few steps. 您只需要建立 XML 檔案、填入適當的項目,並在其中新增您的程式碼。All you need to do is create an XML file, fill in the appropriate elements, and add your code to it. 您也可以將參考和取代參數新增至程式碼。You can also add references and replacement parameters to your code. 您可以使用 [程式碼片段管理員] ([工具] > [程式碼片段管理員]) 上的 [匯入] 按鈕,將程式碼片段新增至 Visual Studio 安裝。You can add the snippet to your Visual Studio installation by using the Import button on the Code Snippets Manager (Tools > Code Snippets Manager).

程式碼片段範本Snippet template

以下是基本程式碼片段範本:The following is the basic snippet template:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title></Title>
        </Header>
        <Snippet>
            <Code Language="">
                <![CDATA[]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

建立程式碼片段Create a code snippet

  1. 在 Visual Studio 中建立新的 XML 檔案,並新增上面所示的範本。Create a new XML file in Visual Studio and add the template shown above.

  2. 在 Title 項目中,填入程式碼片段標題,例如 "Hello World VB"。Fill in the title of the snippet, e.g. "Hello World VB", in the Title element.

  3. Code 元素的 Languages 屬性中,填入程式碼片段的語言。Fill in the language of the snippet in the Language attribute of the Code element. 在此範例中,使用 "VB"。For this example, use "VB".

  4. 例如,在 Code 項目的 CDATA 區段中新增一些程式碼:Add some code in the CDATA section inside the Code element, for example:

    <Code Language="VB">
        <![CDATA[Console.WriteLine("Hello, World!")]]>
    </Code>
    
  5. 將程式碼片段儲存為 VBCodeSnippet.snippetSave the snippet as VBCodeSnippet.snippet.

將程式碼片段新增至 Visual StudioAdd a code snippet to Visual Studio

  1. 您可以使用 [程式碼片段管理員],將自己的程式碼片段新增至 Visual Studio 安裝。You can add your own snippets to your Visual Studio installation by using the Code Snippets Manager. 開啟 [程式碼片段管理員] ([工具] > [程式碼片段管理員])。Open the Code Snippets Manager (Tools > Code Snippets Manager).

  2. 按一下 [匯出] 按鈕。Click the Import button.

  3. 移至您在先前程序中儲存程式碼片段的位置,並選取它,然後按一下 [開啟]。Go to the location where you saved the code snippet in the previous procedure, select it, and click Open.

  4. [匯入程式碼片段] 對話方塊隨即開啟,要求您從右窗格的選項中選擇要新增程式碼片段的位置。The Import Code Snippet dialog opens, asking you to choose where to add the snippet from the choices in the right pane. 其中一個選項應該是 [我的程式碼片段]。One of the choices should be My Code Snippets. 選取它,然後依序按一下 [完成] 和 [確定]。Select it and click Finish, then OK.

  5. 程式碼片段會複製至下列位置:The snippet is copied to the following location:

    %USERPROFILE%\Documents\Visual Studio 2017\Code Snippets\Visual Basic\My Code Snippets%USERPROFILE%\Documents\Visual Studio 2017\Code Snippets\Visual Basic\My Code Snippets

  6. 開啟 Visual Basic 專案,並開啟程式碼檔,來測試程式碼片段。Test your snippet by opening a Visual Basic project and opening a code file. 在檔案中,選擇右鍵功能表中的 [程式碼片段] > [插入程式碼片段],然後選擇 [我的程式碼片段]。In the file choose Snippets > Insert Snippet from the right-click menu, then My Code Snippets. 您應該會看到名為 My Visual Basic Code Snippet 的程式碼片段。You should see a snippet named My Visual Basic Code Snippet. 對它按兩下。Double-click it.

    Console.WriteLine("Hello, World!") 會插入至程式碼檔中。Console.WriteLine("Hello, World!") is inserted in the code file.

新增描述和捷徑欄位Add description and shortcut fields

  1. 描述欄位會提供您的程式碼片段在 [程式碼片段管理員] 中檢視時的詳細資訊。Description fields give more information about your code snippet when viewed in the Code Snippets Manager. 捷徑是使用者可鍵入以插入程式碼片段的標記。The shortcut is a tag that users can type in order to insert your snippet. 開啟檔案 %USERPROFILE%\Documents\Visual Studio 2017\Code Snippets\Visual Basic\My Code Snippet\VBCodeSnippet.snippet,以編輯您已新增的程式碼片段。Edit the snippet you have added by opening the file %USERPROFILE%\Documents\Visual Studio 2017\Code Snippets\Visual Basic\My Code Snippet\VBCodeSnippet.snippet.

  2. AuthorDescription 項目新增至 Header 項目,並填入其資料。Add Author and Description elements to the Header element, and fill them in.

  3. Header 項目看起來應該類似這樣:The Header element should look something like this:

    <Header>
        <Title>Hello World VB</Title>
        <Author>Myself</Author>
        <Description>Says Hello to the world.</Description>
    </Header>
    
  4. 開啟 [程式碼片段管理員],然後選取程式碼片段。Open the Code Snippets Manager and select your code snippet. 在右窗格中,您應該會看到現在已填入 [描述] 和 [作者] 欄位。In the right pane you should see that the Description and Author fields are now populated.

  5. 若要新增捷徑,請新增 Shortcut 項目以及 AuthorDescription 項目:To add a shortcut, add a Shortcut element alongside the Author and Description element:

    <Header>
        <Title>Hello World VB</Title>
        <Author>Myself</Author>
        <Description>Says Hello to the world.</Description>
        <Shortcut>hello</Shortcut>
    </Header>
    
  6. 重新儲存程式碼片段檔案。Save the snippet file again.

  7. 若要測試捷徑,請開啟 Visual Basic 專案,並開啟程式碼檔。To test the shortcut, open a Visual Basic project and open a code file. 在檔案中鍵入 hello,並按 Tab 兩次。Type hello in the file and press Tab twice.

    會插入程式碼片段程式碼。The snippet code is inserted.

新增 References 和 ImportsAdd references and imports

  1. 您可以使用 References 項目新增專案的參考,並使用 Imports 項目新增 Imports 宣告 You can add a reference to a project by using the References element, and add an Imports declaration by using the Imports element. (這也適用於 C#)。例如,如果您將程式碼範例中的 Console.WriteLine 變更為 MessageBox.Show,則可能需要將 System.Windows.Forms.dll 組件新增至專案。(This works for C# as well.) For example, if you change Console.WriteLine in the code example to MessageBox.Show, you may need to add the System.Windows.Forms.dll assembly to the project.

  2. 開啟程式碼片段。Open your snippet.

  3. Snippet 項目下新增 References 項目:Add the References element under the Snippet element:

    <References>
        <Reference>
            <Assembly>System.Windows.Forms.dll</Assembly>
        </Reference>
    </References>
    
  4. Snippet 項目下新增 Imports 項目:Add the Imports element under the Snippet element:

    <Imports>
        <Import>
           <Namespace>System.Windows.Forms</Namespace>
        </Import>
    </Imports>
    
  5. CDATA 區段變更如下:Change the CDATA section to the following:

    <![CDATA[MessageBox.Show("Hello, World!")]]>
    
  6. 儲存程式碼片段。Save the snippet.

  7. 開啟 Visual Basic 專案,並新增程式碼片段。Open a Visual Basic project and add the snippet.

  8. 您會在程式碼檔案頂端看到 Imports 陳述式:You will see an Imports statement at the top of the code file:

    Imports System.Windows.Forms
    
  9. 查看專案的屬性。Look at the project's properties. [參考] 索引標籤會包含 System.Windows.Forms.dll 的參考。The References tab includes a reference to System.Windows.Forms.dll.

新增取代Add replacements

  1. 您可能想要讓使用者取代程式碼片段的各部分;例如,如果您新增變數,而且想要使用者將變數取代為目前專案中的變數。You may want parts of your code snippets to be replaced by the user, for example if you add a variable and want the user to replace the variable with one in the current project. 您可以提供兩種類型的取代:常值和物件。You can provide two types of replacements: literals and objects. 常值是某種類型的字串 (字串常值、變數名稱或數值的字串表示法)。Literals are strings of some type (string literals, variable names, or string representations of numeric values). 物件是字串以外的某種類型的執行個體。Objects are instances of some type other than a string. 在此程序中,您會宣告常值取代和物件取代,並變更程式碼以參考這些取代。In this procedure you will declare a literal replacement and an object replacement, and change the code to reference these replacements.

  2. 開啟程式碼片段。Open your snippet.

  3. 此範例使用 SQL 連接字串,因此您需要變更 ImportsReferences 項目來新增適當的參考:This example uses a SQL connection string, so you need to change the Imports and References elements to add the appropriate references:

    <References>
        <Reference>
            <Assembly>System.Data.dll</Assembly>
        </Reference>
        <Reference>
            <Assembly>System.Xml.dll</Assembly>
        </Reference>
    </References>
    <Imports>
        <Import>
            <Namespace>System.Data</Namespace>
        </Import>
        <Import>
            <Namespace>System.Data.SqlClient</Namespace>
        </Import>
    </Imports>
    
  4. 若要宣告 SQL 連接字串的常值取代,請在 Snippet 元素下新增 Declarations 元素,並在其中新增具有取代識別碼、工具提示和預設值之子元素的 Literal 元素:To declare a literal replacement for the SQL connection string, add a Declarations element under the Snippet element, and in it add a Literal element with sub-elements for the ID, the tooltip, and the default value for the replacement:

    <Declarations>
        <Literal>
            <ID>SqlConnString</ID>
            <ToolTip>Replace with a SQL connection string.</ToolTip>
            <Default>"SQL connection string"</Default>
        </Literal>
    </Declarations>
    
  5. 若要宣告 SQL 連線的物件取代,請新增 Declarations 項目內的 Object 項目,並新增識別碼、物件類型、工具提示和預設值的子項目。To declare an object replacement for the SQL connection, add an Object element inside the Declarations element, and add sub-elements for the ID, the type of the object, the tooltip, and the default value. 產生的 Declarations 項目看起來應該像這樣:The resulting Declarations element should look like this:

    <Declarations>
        <Literal>
            <ID>SqlConnString</ID>
            <ToolTip>Replace with a SQL connection string.</ToolTip>
            <Default>"SQL connection string"</Default>
        </Literal>
        <Object>
            <ID>SqlConnection</ID>
            <Type>System.Data.SqlClient.SqlConnection</Type>
            <ToolTip>Replace with a connection object in your application.</ToolTip>
            <Default>dcConnection</Default>
        </Object>
    </Declarations>
    
  6. 在程式碼區段中,您可以參考使用 $ 符號括住的取代 (例如 $replacement$):In the code section, you reference the replacements with surrounding $ signs, for example $replacement$:

    <Code Language="VB" Kind="method body">
        <![CDATA[Dim daCustomers As SqlDataAdapter
            Dim selectCommand As SqlCommand
    
            daCustomers = New SqlClient.SqlDataAdapter()
            selectCommand = new SqlClient.SqlCommand($SqlConnString$)
            daCustomers.SelectCommand = selectCommand
            daCustomers.SelectCommand.Connection = $SqlConnection$]]>
    </Code>
    
  7. 儲存程式碼片段。Save the snippet.

  8. 開啟 Visual Basic 專案,並新增程式碼片段。Open a Visual Basic project and add the snippet.

  9. 程式碼應該如下,其中會以淺橙色反白顯示 SQL connection stringdcConnection 取代。The code should look like the following, where the replacements SQL connection string and dcConnection are highlighted in light orange. 選擇 [索引標籤],以覽兩個不同的索引標籤。Choose Tab to navigate from one to the other.

    Dim daCustomers As SqlDataAdapter
    Dim selectCommand As SqlCommand
    
    daCustomers = New SqlClient.SqlDataAdapter()
    selectCommand = New SqlClient.SqlCommand("SQL connection string")
    daCustomers.SelectCommand = selectCommand
    daCustomers.SelectCommand.Connection = dcConnection
    

另請參閱See also