模板的好處自不必多說, 一來可以減少大家的重複鍵入, 二來也可以更容易的保持組裏面大家編寫的代碼的風格統一, 比如公司要求給源文件編寫統一格式的Copyright等等.
使用Resharp可以爲Visual Studio定義模板.
菜單欄點擊[ReSharper]->[Live Templates..], 可以打開Templates Explorer.
通過Templates Explorer可以執行瀏覽, 添加, 刪除,編輯, 以及導入導出等各種模板操作
模板種類以及對應的默認快捷鍵如下:
Live Templates: Ctrl+J
Surround Templates : Ctrl+Alt+J
File Templates: Ctrl+Alt+Ins
關於這三個種類的介紹, 可以參考這個鏈接:Live Templates
,
Resharper預定義好了那些模板? 可以參看下面的鏈接.
用戶自定義模板的方法,可以參考這個鏈接
To create a code template from scratch
自定義模板的時候自然少不了宏
ReSharper中, 模板代碼中, 在兩個$之間字符串將被自動識別成一個宏變量.
比如$RETURN_TPYE$等等.
自定義模板中, 很關鍵的一個問題是:
自定義的這些宏變量, 可以被ReSharper自動設置成那些初始值?
這個問題可以參考Resharper官網的這兩個連接:
變量的類型還是比較豐富, 當前是文件名, 當前時間(可自定義格式), 當前用戶等等都可以.
最後, 自定義的Templates可以導入導出爲XML文檔, 在組內共享.
下面的xml是我們導出的一個Copyright模板的代碼, 對於宏變量我們可以看出他對應的實現函數.
形如下面這樣:< Variable name = "FILE_NAME" expression = "getFileName() " initialRange = "0" />
<TemplatesExport family="Live Templates"> <Template uid="3b0a789b-3b12-4c6c-a1fc-36d2ea58118c" shortcut="copyright" description="sCopyRight template$" text="///////////////////////////////////////////////////////////
// $FILE_NAME$
// Version:1.0.0
// Created on: $DATE_TIME$
// Original author: $AUTHOR$
// <copyright file="$FILE_NAME$" company="OurCompanyName">
// Copyright (C) $YEAR$ Oki Data Corporation
// </copyright>
// <summary>Defines the $FILE_NAME_NO_EXTENSION$ class.</summary>
///////////////////////////////////////////////////////////
" reformat="True" shortenQualifiedReferences="True"> <Scopes> <Scope type="Everywhere" /> </Scopes> <Categories /> <Variables> <Variable name="FILE_NAME" expression="getFileName()" initialRange="0" /> <Variable name="DATE_TIME" expression="getCurrentTime("yyyy/MM/dd hh:mm:ss")" initialRange="0" /> <Variable name="AUTHOR" expression="getUserName()" initialRange="0" /> <Variable name="YEAR" expression="getCurrentDate("yyyy")" initialRange="0" /> <Variable name="FILE_NAME_NO_EXTENSION" expression="getFileNameWithoutExtension()" initialRange="0" /> </Variables> <CustomProperties /> </Template> </TemplatesExport>