﻿# 如何將 Visual Studio 2008 的 prop 程式碼片段換成舊版的

我們常用的 prop 程式碼片段(Code Snippet)可以自動產生一組 Property 屬性的定義，從 Visual Studio 2005 就有了。由於 C# 3.0 新增了一個功能叫做 **Automatic properties**，可以簡化 Property 的定義語法，導致 Visual Studio 2008 預設的 prop 程式碼片段都被換成「新版」的了。雖然一開始覺得蠻方便的，但是當 Property 需要客製化調整的時候 ( 使用舊語法 ) 就反而變的礙手礙腳的。

![Property](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/7df81222e4618cb7f3f1-image_3.png "Property")

而事實上 C# 3.0 的 Automatic properties 只是將原本 C# 2.0 的 Property 定義的語法「包裝」過而已，實際上當程式被編譯成組件時，C# 編譯器(Compiler)還是會將 Property 展開，他會將省略的 Field (欄位) 自動取一個變數名稱，如下圖示是我將程式編譯後再用 [Reflector](http://www.red-gate.com/products/reflector/) 反解出來的欄位名稱。

![Reflector for Automatic property](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/0906f3a59c33596b3139-image_6.png "Reflector for Automatic property")

所以為了要讓我的 Visual Studio 2008 可以支援「舊版的」prop 程式碼片段，我自己改寫了一個 **propo.snippet** 程式碼片段定義檔，各位只要將該檔案建立好並複製到 **C:\\Program Files\\Microsoft Visual Studio 9.0\\VC#\\Snippets\\1033\\Visual C#** 目錄下即可立即套用，不用重開 Visual Studio 2008。

propo.snippet 程式碼片段內容如下：（快速鍵我改成 propo ）

```xml
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>propo</Title>
			<Shortcut>propo</Shortcut>
			<Description>Code snippet for a OLD style property (Visual Studio 2005)</Description>
			<Author>Will Huang</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>field</ID>
					<ToolTip>Field Name</ToolTip>
					<Default>mName</Default>
				</Literal>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>Name</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[private $type$ $field$;
			public $type$ $property$ 
			{ 
				get {return this.$field$;} 
				set {this.$field$ = value;} 
			}

			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>
```

如此一來就可以同時擁有兩種不同的 prop 程式碼片段了！

**相關連結**

-   [建立和使用 IntelliSense 程式碼片段](http://msdn.microsoft.com/zh-tw/library/ms165392.aspx)
-   [Creating and Using IntelliSense Code Snippets](http://msdn.microsoft.com/en-gb/library/ms165392.aspx)
