You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在csproj中用通配符配置T4模板,避免自动添加项目条目?

问题

项目中有多个TT文件,原本每个文件都需要在csproj中添加重复的ItemGroup条目:

<ItemGroup>
  <Compile Update="Sample.cs">
    <DesignTime>True</DesignTime>
    <AutoGen>True</AutoGen>
    <DependentUpon>Sample.tt</DependentUpon>
  </Compile>
</ItemGroup>

<ItemGroup>
  <None Update="Sample.tt">
    <Generator>TextTemplatingFileGenerator</Generator>
    <LastGenOutput>Sample.cs</LastGenOutput>
  </None>
</ItemGroup>

为避免手动添加重复配置,尝试用通配符批量配置csproj:

<ItemGroup>
  <Compile Update="**/*.tt.cs">
    <DesignTime>True</DesignTime>
    <AutoGen>True</AutoGen>
    <DependentUpon>%(Filename)</DependentUpon>
  </Compile>
  <None Update="**/*.tt">
    <Generator>TextTemplatingFileGenerator</Generator>
    <LastGenOutput>%(Filename).tt.cs</LastGenOutput>
  </None>
</ItemGroup>

同时在TT文件中设置输出扩展名:

<#@ output extension="tt.cs" #>

目前T4模板可正常工作,但保存TT文件时,csproj中仍会自动添加如下单独条目:

<ItemGroup>
  <Compile Update="Sample.tt.cs">
    <DesignTime>True</DesignTime>
  </Compile>
</ItemGroup>

如何阻止这种自动添加条目的操作?

解决方案

方法1:标记生成文件属性

在通配符配置的Compile项中添加<Generated>True</Generated>属性,明确告诉Visual Studio该文件是自动生成的,无需单独添加条目:

<ItemGroup>
  <Compile Update="**/*.tt.cs">
    <DesignTime>True</DesignTime>
    <AutoGen>True</AutoGen>
    <DependentUpon>%(Filename)</DependentUpon>
    <Generated>True</Generated>
  </Compile>
  <None Update="**/*.tt">
    <Generator>TextTemplatingFileGenerator</Generator>
    <LastGenOutput>%(Filename).tt.cs</LastGenOutput>
  </None>
</ItemGroup>

方法2:禁用默认编译项自动同步

在csproj的PropertyGroup中添加配置,关闭VS自动检测并添加编译项的功能:

<PropertyGroup>
  <EnableDefaultCompileItems>False</EnableDefaultCompileItems>
</PropertyGroup>

注意:此设置会禁用全局默认的编译项自动识别,需确保你的通配符配置已覆盖所有需要编译的文件,避免遗漏。

方法3:修改VS全局设置

打开Visual Studio的「工具 → 选项」,进入「项目和解决方案 → 常规」,取消勾选「自动更新项目以匹配文件系统」。
该设置为全局生效,会影响所有项目,仅在需要全局禁用此功能时使用。

内容的提问来源于stack exchange,提问作者usausa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:54:12