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

如何将Source Generator作为NuGet包添加到C# .NET5项目

如何将Source Generator作为NuGet包添加到C# .NET5项目?

如果是通过本地项目引用的方式接入Source Generator,配置方式如下:

<ItemGroup>
  <ProjectReference Include="..\xyz.SourceGenerators\xyz.SourceGenerators.csproj"
    OutputItemType="Analyzer"
    ReferenceOutputAssembly="false"
    SetTargetFramework="TargetFramework=netstandard2.0" />
</ItemGroup>

如果要通过NuGet包的形式接入,使用PackageReference节点的配置方式和项目引用逻辑类似,只需要补充对应属性即可,示例配置如下:

<ItemGroup>
  <!-- 替换Include和Version为你实际使用的Source Generator包信息 -->
  <PackageReference Include="xyz.SourceGenerators" Version="1.0.0"
    OutputItemType="Analyzer"
    ReferenceOutputAssembly="false" />
</ItemGroup>

两个配置属性的作用说明:

  • OutputItemType="Analyzer":标记该包为分析器/源生成器类型,告知MSBuild在编译阶段执行生成逻辑,不会将包作为普通依赖输出到bin目录
  • ReferenceOutputAssembly="false":禁止项目直接引用源生成器的程序集,避免编译时出现多余的依赖引用错误

注:NuGet引用不需要额外添加SetTargetFramework属性,只要你使用的Source Generator包本身兼容netstandard2.0即可正常在.NET5项目中运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:09:00