在VisualStudio2005和VisualStudio2008中,我們輸入prop然後輸入Tab鍵就可以智能插入一段代碼,非常方便。如:
如果夠懶的話,也可以自己建立自己經常寫的程式碼片段來提高寫代碼的效率,在VisualStudio2005和VisualStudio2008中,開啟菜單Tools – Code Snippets Manager (Ctrl+K, Ctrl+B)可以查看Code Snippets的位置:
建立一個自己的Singleton程式碼片段:(Singleton.snippet)
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Singleton</Title>
<Shortcut>singleton</Shortcut>
<Description>Creates a Singleton Class following the discussion on that post of mine:
http://blogs.ugidotnet.org/piyo/archive/2005/09/14/Singleton_C_NET.aspx</Description>
<HelpUrl />
<Author>Simone Chiaretta</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Keywords />
</Header>
<Snippet>
<References />
<Imports />
<Declarations>
<Literal Editable="true">
<ID>className</ID>
<ToolTip>Here the name of your singleton class</ToolTip>
<Default>Singleton</Default>
<Function />
</Literal>
</Declarations>
<Code Language="csharp" Kind="any" Delimiter="$">public class $className$
{
private static readonly $className$ Instance = new $className$();
static $className$()
{
}
public static $className$ GetInstance()
{
return Instance;
}
} </Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
其中的header部分簡單描述了關於這個snippets的資訊,如名稱,捷徑,作者,備忘等。在<snippets>節點下,則逐個定義了在snippets中出現的屬性,其中<default>指出了該屬性預設的值。而在關鍵區段<code>,用<![CDATA]>的方式定義了snippets的基礎架構,其中用$參數名的方式定義每個屬性,十分簡單。
(可以隨便用編輯器,可以用微軟的CodeSnippet編輯器,這裡下載)
然後在VisualStudio2005和VisualStudio2008中,開啟菜單Tools – Code Snippets Manager (Ctrl+K, Ctrl+B),點擊匯入,選擇儲存的Singleton.snippet檔案位置即可。
以後在寫代碼時,輸入singleton,然後按Tab鍵,即可插入一個Singleton模式的類。游標會自動停在類名上。(也可以點擊滑鼠右鍵,選擇Insert Snippet…,然後選擇自己的CodeSnippet即可。
同樣可以建立自己定製的CodeSnippets,例如類模板,NUnit模板,讀取Xml檔案的程式碼片段,儲存Xml的程式碼片段,拋出Exception的程式碼片段,String.IsNullOrEmpty判斷等等,來提高自己寫代碼的效率。
(其它Visual studio技巧:工欲善其事,必先利其器——圖文並茂詳解VisualStudio提示一)
VS2010外掛程式:Snippet Designer
有一個VisualStudio2010外掛程式SnippetDesigner. 選中一段代碼,然後右鍵“Export as Snippet”就可以很方便的管理和建立Snippet了。