![](/img/trans.png)
[英]T4 Template failing with MissingMethodException on imported assembly
[英]Save T4 output to file from an imported assembly
我正在嘗試創建一個可以導入到文本模板中的庫,以使我的模板更易於使用。 我的庫的主要參數是模板對象。 雖然這不是最佳實踐,但我還沒有找到可行的解決方法。 一旦我引用了庫中的模板對象,我就會嘗試將模板的輸出保存到另一個位置。 這是庫的代碼。
namespace Templates
{
public class Helper
{
private readonly object _thisTemplate = null;
public Helper(object input) => _thisTemplate = input;
public void SaveToFile(string path)
{
var transformTextMethod = _thisTemplate.GetType().GetMethod("TransformText");
var content = transformTextMethod.Invoke(_thisTemplate, new object[] {}).ToString();
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
{
using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs))
{
sr.WriteLine(content);
sr.Flush();
}
}
}
}
}
這是我用來調用這個庫的模板
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="$(ProjectDir)$(OutDir)$(TargetFileName)" #>
<#@ output extension="\\" #>
<#
var helper = new Templates.Helper(this);
var outputFile = this.Host.TemplateFile.Replace(".tt",".txt");
#>
<#= DateTime.Now.ToString() #>
<# helper.SaveToFile(outputFile); #>
該模板具有<#@ output extension="\\\\" #>
以便不產生任何輸出,而是我嘗試使用SaveToFile
方法保存它。 當我嘗試使用 TextTemplatingFileGenerator 運行它時,它會導致 Visual Studio 崩潰。 為了獲得更多信息,我嘗試將它作為 TextTemplatingFilePreProcessor 運行,但效果很好。
誰能告訴我我做錯了什么?
我也接受了 BurnsBA 的建議並調整了模板以與 TextTransform.exe 一起使用,但是這也會崩潰
作為一種解決方法,我在解決方案目錄的模板文件夾中有一個基本模板,並在其中添加了這樣的方法......
<#+
void SaveFile(string path)
{
var content = this.GenerationEnvironment.ToString();
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
{
using (System.IO.StreamWriter str = new System.IO.StreamWriter(fs))
{
str.WriteLine(content.Trim("\n\r".ToCharArray()));
str.Flush();
}
}
}
#>
...然后使用像這樣的包含指令在我的模板頂部引用此基本模板...
<#@ include file="$(SolutionDir)Templates\BaseTemplate.ttinclude" #>
如果有人有任何想法,我仍然想找到一種可行的方法來在類中保存此功能?
你有一個無限循環......
在Helper.SaveToFile
調用TransformText
會導致評估模板,該模板調用Helper.SaveToFile
再次調用TransformText
等。
基類實現之所以有效,是因為您使用的是GenerationEnvironment
屬性,該屬性不會再次評估模板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.