一直想找個快捷鍵,是可以自定義插入代碼段的,今天看到一篇文章。
原文:http://developer.51cto.com/art/201006/208136.htm
創建自定義代碼段
首先在項目中插入一個新的XML文件,取名爲TryCatchFinally.snippet,注意文件名的後綴是.snippet,然後在編輯器窗口點擊右鍵,選擇“插入代碼段”*“代碼段”,創建一個基本的XML代碼段模板,代碼如下:
- <CodeSnippet Format="1.0.0"
- xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
- <Header>
- <Title>title</Title>
- <Author>author</Author>
- <Shortcut>shortcut</Shortcut>
- <Description>description</Description>
- <SnippetTypes>
- <SnippetType>SurroundsWith</SnippetType>
- <SnippetType>Expansion</SnippetType>
- </SnippetTypes>
- </Header>
- <Snippet>
- <Declarations>
- <Literal>
- <ID>name</ID>
- <Default>value</Default>
- </Literal>
- </Declarations>
- <Code Language="XML">
- <![CDATA[<test>
- <name>$name$</name>
- $selected$ $end$</test>]]>
- </Code>
- </Snippet>
- </CodeSnippet>
正如你所看到的,默認的模板包括兩個代碼段類型,因爲我這裏是要創建一個Expansion代碼段,因此去掉<SnippetType>SurroundsWith</SnippetType>標籤。
然後將title改爲“Try Catch Finally”,Shortcut改爲“trycf”,Description改爲“Adds a try-catch-finally block”。
Literal標籤定義了代碼段中可編輯的值,在try-catch-finally代碼段中,我們希望用戶可修改捕獲到的異常(Exception)類型,ID標籤是可編輯值的名字,因此將其改爲“ExceptionName”,Default標籤指定了可編輯字段的默認值,我想捕獲所有的異常,因此我將它的值改爲“Exception”。
最後,code小節部分包括代碼段插入時自動填充的代碼,將language改爲“CSharp”,code部分的全部代碼如下:
- <Code Language="CSharp">
- <![CDATA[
- try
- {
- }
- catch($ExceptionName$)
- {
- }
- finally
- {
- }
- ]]>
- </Code>
TryCatchFinally.snippet文件的最終代碼如下:
- <?xml version="1.0" encoding="utf-8" ?>
- <CodeSnippet Format="1.0.0"
- xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
- <Header>
- <Title>Try Catch Finally</Title>
- <Author>umair</Author>
- <Shortcut>trycf</Shortcut>
- <Description>Adds a try-catch-finally block</Description>
- <SnippetTypes>
- <SnippetType>Expansion</SnippetType>
- </SnippetTypes>
- </Header>
- <Snippet>
- <Declarations>
- <Literal>
- <ID>ExceptionName</ID>
- <Default>Exception</Default>
- </Literal>
- </Declarations>
- <Code Language="CSharp">
- <![CDATA[
- try
- {
- }
- catch($ExceptionName$)
- {
- }
- finally
- {
- }
- ]]>
- </Code>
- </Snippet>
- </CodeSnippet>
在Visual Studio中載入自定義代碼段
在Visual Studio中有兩種方法載入上面的自定義代碼段:
最直接的方法是將.snippet文件放在Visual Studio的代碼段目錄下,默認位置是C:\Users\<UserName>\Documents\Visual Studio 2010\Code Snippets\,這個目錄會根據所使用的語言生成對應的子目錄,如我們這裏使用的C#,因此應該將自定義代碼段文件放在Visual C#子目錄下,Visual Studio會自動發現新放進去的.snippet文件,無需重啓Visual Studio。
第二種方法是將.snippet文件導入到Visual Studio中,選擇“工具”*“代碼段管理器”(Ctrl+K,Ctrl+B),在代碼段管理器中,點擊“導入”按鈕,瀏覽到.snippet文件所在位置,選擇它,然後點擊“確定”。
使用自定義代碼段
在Visual Studio的編輯器中,輸入自定義代碼段名字的前幾個字符,按Tab鍵,在彈出的代碼提示窗口中便可看到前面自定義的代碼段名稱(快捷名稱和完全名稱Tip提示),如下圖所示:
圖 1 輸入try,在彈出的代碼提示窗口中可看到自己定義的代碼段名
你也可以在編輯器中按CTRL+K,再按CTRL+X調出“插入代碼段”菜單,如下圖所示:
圖 2 插入代碼段菜單
選擇菜單中的“My Code Snippets”,再選擇前面添加的TryCatchFinally自定義代碼段,如下圖所示:
圖 3 插入TryCatchFinally自定義代碼段
正如你所看到的,在Visual Studio 2010中,添加自定義代碼段,裝載自定義代碼段文件和使用自定義代碼都變得更加簡單了,這一提高生產力的功能你應該多多使用。