September 19, 2012

自訂Visual Studio樣版參數

接續修改Visual Studio內建樣版一文,檢視一下Class.cs檔案
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
 class $safeitemrootname$
 {
 }
}

VS的樣版提供了一些預設參數如上述範例的$rootnamespace$,如果需要的話也可自訂參數。

開啟Class.vstemplate,在<TemplateContent>中加入<CustomParameters>節點。如以下20至22行程式碼中,加入了一個名為developer的參數,參數值為Pete

<?xml version="1.0" encoding="utf-8"?>
<VSTemplate Version="3.0.0" Type="Item" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2245" />
    <Description Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2262" />
    <Icon Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="4515" />
    <TemplateID>Microsoft.CSharp.Class</TemplateID>
    <ProjectType>CSharp</ProjectType>
    <SortOrder>90</SortOrder>
    <RequiredFrameworkVersion>2.0</RequiredFrameworkVersion>
    <NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
    <DefaultName>Class.cs</DefaultName>
  </TemplateData>
  <TemplateContent>
  <References>
   <Reference>
    <Assembly>System</Assembly>
   </Reference>
  </References>
  <CustomParameters>
   <CustomParameter Name="$developer$" Value="Pete"/>
  </CustomParameters>
    <ProjectItem ReplaceParameters="true">Class.cs</ProjectItem>
  </TemplateContent>
</VSTemplate>

之後在Class.cs即可以$developer$方式使用此參數,如

//------------------------------------------------------------------------------
// Description:
// Created by: $developer$
// Created on:
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
 class $safeitemrootname$
 {
 }
}
修改完後存檔並更新此樣版。接下來新增的類別檔就會將$developer$替換為Pete了。這裡需要注意的一點是,參數的名稱是區分大小寫的。
//------------------------------------------------------------------------------
// Description:
// Created by: Pete
// Created on:
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AdventureWorks.Client.Console
{
    class Class1
    {
    }
}

No comments: