感谢 GitHub.com/Mono/T4,目前您可以通过将其添加到您的 .csproj 文件中来为 .NET Core 和 Visual Studio 构建执行此操作:
<ItemGroup>
<DotNetCliToolReference Include="dotnet-t4-project-tool" Version="2.0.5" />
<TextTemplate Include="**\*.tt" />
</ItemGroup>
<Target Name="TextTemplateTransform" BeforeTargets="BeforeBuild">
<ItemGroup>
<Compile Remove="**\*.cs" />
</ItemGroup>
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet t4 %(TextTemplate.Identity)" />
<ItemGroup>
<Compile Include="**\*.cs" />
</ItemGroup>
</Target>
如果您将模板转换为不同的编程语言,您应该添加类似 <Compile Remove="**\*.vb" /> 和 <Compile Include="**\*.vb" /> 的内容,以便编译这些文件,即使您还没有生成文件。
Remove 和 Include 技巧仅在第一次生成时需要,或者您可以像这样使 XML 更短:
<ItemGroup>
<DotNetCliToolReference Include="dotnet-t4-project-tool" Version="2.0.5" />
<TextTemplate Include="**\*.tt" />
</ItemGroup>
<Target Name="TextTemplateTransform" BeforeTargets="BeforeBuild">
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet t4 %(TextTemplate.Identity)" />
</Target>
然后只运行两次构建(第一次)。如果您已经生成了提交到存储库的文件,那么使用这两个示例进行重建都不会出现问题。
在 Visual Studio 中,您可能希望看到如下内容:
而不是这个:
所以在你的项目文件中添加这样的内容:
<ItemGroup>
<Compile Update="UInt16Class.cs">
<DependentUpon>UInt16Class.tt</DependentUpon>
</Compile>
<Compile Update="UInt32Class.cs">
<DependentUpon>UInt32Class.tt</DependentUpon>
</Compile>
<Compile Update="UInt64Class.cs">
<DependentUpon>UInt64Class.tt</DependentUpon>
</Compile>
<Compile Update="UInt8Class.cs">
<DependentUpon>UInt8Class.tt</DependentUpon>
</Compile>
</ItemGroup>
此处的完整示例:GitHub.com/Konard/T4GenericsExample(包括从单个模板生成多个文件)。