如果您要撰寫 Visual Studio 延伸模組,例如功能表命令或 網域特定語言,您可以使用文字範本服務來轉換文字範本。 取得 STextTemplating 服務,並將它轉換至 ITextTemplating。
取得文字範本化服務
using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.TextTemplating.VSHost;
...
// Get a service provider - how you do this depends on the context:
IServiceProvider serviceProvider = ...; // An instance of EnvDTE, for example
// Get the text template service:
ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
// Process a text template:
string result = t4.ProcessTemplate(filePath, System.IO.File.ReadAllText(filePath));
將參數傳遞至範本
您可以將參數傳遞至範本。 在範本內,您可以使用指令取得參數值 <#@parameter#> 。
對於參數的類型,您必須使用可序列化或封送處理的類型。 也就是說,類型必須以 SerializableAttribute宣告,或必須衍生自 MarshalByRefObject。 此限制是必要的,因為文字範本是在個別的 AppDomain 中執行。 所有內建類型 ( 例如 System.String 和 System.Int32 ) 都是可序列化的。
若要傳遞參數值,呼叫程式碼可以將值放在Session字典中,或放在CallContext中。
下列範例會使用這兩種方法來轉換簡短的測試範本:
using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.TextTemplating.VSHost;
...
// Get a service provider - how you do this depends on the context:
IServiceProvider serviceProvider = dte;
// Get the text template service:
ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost;
// Create a Session in which to pass parameters:
sessionHost.Session = sessionHost.CreateSession();
sessionHost.Session["parameter1"] = "Hello";
sessionHost.Session["parameter2"] = DateTime.Now;
// Pass another value in CallContext:
System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("parameter3", 42);
// Process a text template:
string result = t4.ProcessTemplate("",
// This is the test template:
"<#@parameter type=\"System.String\" name=\"parameter1\"#>"
+ "<#@parameter type=\"System.DateTime\" name=\"parameter2\"#>"
+ "<#@parameter type=\"System.Int32\" name=\"parameter3\"#>"
+ "Test: <#=parameter1#> <#=parameter2#> <#=parameter3#>");
// This test code yields a result similar to the following line:
// Test: Hello 07/06/2010 12:37:45 42
錯誤報告和輸出指引
處理期間發生的任何錯誤都會顯示在 Visual Studio 錯誤視窗中。 此外,您可以指定實作 ITextTemplatingCallback 的回呼,以收到錯誤通知。
如果您想要將結果字串寫入檔案,您可能想要知道範本的指引中 <#@output#> 已指定的副檔名和編碼。 此資訊也將傳遞至您的回撥。 如需詳細資訊,請參閱 T4 輸出指示詞。
void ProcessMyTemplate(string MyTemplateFile)
{
string templateContent = File.ReadAllText(MyTemplateFile);
T4Callback cb = new T4Callback();
// Process a text template:
string result = t4.ProcessTemplate(MyTemplateFile, templateContent, cb);
// If there was an output directive in the MyTemplateFile,
// then cb.SetFileExtension() will have been called.
// Determine the output file name:
string resultFileName =
Path.Combine(Path.GetDirectoryName(MyTemplateFile),
Path.GetFileNameWithoutExtension(MyTemplateFile))
+ cb.fileExtension;
// Write the processed output to file:
File.WriteAllText(resultFileName, result, cb.outputEncoding);
// Append any error messages:
if (cb.errorMessages.Count > 0)
{
File.AppendAllLines(resultFileName, cb.errorMessages);
}
}
class T4Callback : ITextTemplatingCallback
{
public List<string> errorMessages = new List<string>();
public string fileExtension = ".txt";
public Encoding outputEncoding = Encoding.UTF8;
public void ErrorCallback(bool warning, string message, int line, int column)
{ errorMessages.Add(message); }
public void SetFileExtension(string extension)
{ fileExtension = extension; }
public void SetOutputEncoding(Encoding encoding, bool fromOutputDirective)
{ outputEncoding = encoding; }
}
程式碼可以使用類似下列的範本檔案進行測試:
<#@output extension=".htm" encoding="ASCII"#>
<# int unused; // Compiler warning "unused variable"
#>
Sample text.
編譯器警告會出現在 Visual Studio 錯誤視窗中,而且也會產生對 ErrorCallback的呼叫。
參考參數
您可以使用衍生自 MarshalByRefObject的參數類別,將值從文字範本傳遞出。
相關文章
若要從預先處理的文字範本產生文字:呼叫 TransformText() 產生類別的方法。 如需詳細資訊,請參閱 T4 文字範本與執行階段文字生成。
若要在 Visual Studio 延伸模組外部產生文字:定義自訂主機。 如需詳細資訊,請參閱 使用自訂主機處理文字範本。
若要產生稍後可編譯和執行的原始程式碼:呼叫 ITextTemplate 的 PreprocessTemplate 方法。