[英]T4 text template unable to call other code
打开VisualStudio2022,新建一个net6.0
class库。
创建 class 以在 T4 模板中使用并创建 T4 模板并使用 class。
Class:
namespace ClassLibraryT4
{
public class Class1
{
public static string DoTheThing() { return "TheThing"; }
}
}
现在构建项目,使其dll
文件存在于磁盘上。
T4:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="$(SolutionDir)ClassLibraryT4\bin\Debug\net6.0\ClassLibraryT4.dll" #>
<#@ import namespace="ClassLibraryT4" #>
<#@ output extension=".cs" #>
namespace ClassLibraryT4
{
public class TheGeneratedClass
{
private const string _TheThing = "<# Class1.DoTheThing(); #>";
}
}
T4 现在无法运行,因为
n“对象”类型是在未引用的程序集中定义的。 您必须添加对程序集“System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”的引用。
如果我添加到 T4:
<#@ assembly name="System.Runtime"#>
然后我现在得到
Error Running transformation: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
at Microsoft.VisualStudio.TextTemplating6765B00A4659E4D1054752E9A2C829A21EECD20197C4EDDD8F5675E0DB91730A0DFF4528F1622E70821097EC90F6A2D0DE05F4739B3E0CD1BCAF45AAA20D419D.GeneratedTextTransformation.TransformText()
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Microsoft.VisualStudio.TextTemplating.TransformationRunner.PerformTransformation()
T4s可以工作吗?
似乎不可能使用任何外部代码; 这在 T4中确实有效:
private const string _TheThing = "<#= 5+2 #>";
这也是:
private const string _TheThing = "<#= Thing() #>";
...
<#+
private static string Thing() {
return "thing";
}
#>
但这也有_Could not load file or assembly System.Runtime...`问题:
<#+
private static string Thing() {
return Class1o.DoTheThing();
}
#>
T4s可以工作吗? 是的。 您只需要确保所有使用的 dll 都适用于 x86 架构。 这是 Visual Studio 的限制,因为它是 32 位应用程序。
最安全的方法是使用netstandard2.0
将任何程序集加载到 T4 模板中。 如果您仅包含普通的 C# 代码(通过 include 指令),那么即使在调整汇编指令一段时间后它使用net6.0
API,您也可以摆脱它。 但是,您需要对其进行调整,使其适用于 Visual Studio和MSBuild 主机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.