我正在尝试创建一个可以导入文本模板的库,以使模板更易于使用。我的库的主要参数是模板对象。虽然这不是最佳做法,但我还没有找到可行的解决方法。一旦我在库中引用了模板对象,便试图将模板的输出保存到另一个位置。 这是该库的代码。
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指令在我的模板顶部引用此基本模板...
<#@ include file="$(SolutionDir)Templates\BaseTemplate.ttinclude" #>
如果有人有任何想法,我还是想找到一种可行的方法来在班级中保存此功能?
答案 0 :(得分:1)
您有一个无限循环...
在Public Function IsOnQX(ByVal InputCell As Range, ByVal Month As Long) As Integer
Dim ActualQuarter As Integer
Dim PastQuarter As Integer
If (Month < 1) Or (Month > 12) Then
Call Err.Raise(6) ' Value out of Bounds '
End If
ActualQuarter = (Month(Date) + 2) \ 3
PastQuarter = (Month(InputCell.Value) + 2) \ 3
If IsEmpty(InputCell) Or (PastQuarter < ActualQuarter) Then
IsOnQX = 1
Else
IsOnQX = 0
End If
End Function
中调用TransformText
导致模板被评估,该模板调用Helper.SaveToFile
,后者再次调用Helper.SaveToFile
等,等等。
基类实现有效,因为您正在使用TransformText
属性,该属性不会再次评估模板。