[英]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.