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

C# Source Generator未运行:按官方教程操作无输出问题排查

排查Source Generator无输出的常见问题

针对你按照官方教程实现Source Generator后控制台项目dotnet run无输出的情况,从以下几个核心环节排查:

1. 生成器项目配置是否正确

  • 确认TestSourceGenerator.csproj中包含以下关键配置:
    <PropertyGroup>
      <TargetFramework>netstandard2.0</TargetFramework>
      <IsRoslynComponent>true</IsRoslynComponent>
    </PropertyGroup>
    
    Source Generator必须以netstandard2.0为目标框架,且IsRoslynComponent设为true才能被Roslyn识别。
  • 检查是否引用了正确的分析器包,需添加:
    <ItemGroup>
      <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.6.0" PrivateAssets="all" />
      <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
    </ItemGroup>
    
    版本需与你的.NET 7 SDK兼容(4.x系列适配.NET 7)。

2. 生成器代码是否符合要求

  • 确保TestGenerator.cs类上添加了[Generator]特性,且正确实现ISourceGenerator接口:
    using Microsoft.CodeAnalysis;
    
    [Generator]
    public class TestGenerator : ISourceGenerator
    {
        public void Initialize(GeneratorInitializationContext context) { }
    
        public void Execute(GeneratorExecutionContext context)
        {
            // 必须生成可被调用的代码,示例如下:
            var source = @"
    namespace GeneratedCode
    {
        public static class HelloGenerator
        {
            public static void Print()
            {
                System.Console.WriteLine(""Generated code output!"");
            }
        }
    }";
            context.AddSource("HelloGenerator.cs", source);
        }
    }
    
    若未添加[Generator]特性,或Execute方法未生成有效可执行代码,生成器不会运行。

3. 控制台项目引用生成器的方式是否正确

  • 控制台项目Test.csproj中引用生成器项目时,必须设置正确的输出类型:
    <ProjectReference Include="..\TestSourceGenerator\TestSourceGenerator.csproj"
                      OutputItemType="Analyzer"
                      ReferenceOutputAssembly="false" />
    
    缺少OutputItemType="Analyzer"会导致生成器无法嵌入到编译过程中。
  • 确认Program.cs中调用了生成器生成的代码:
    GeneratedCode.HelloGenerator.Print();
    
    即使生成器正确生成了代码,若未在主程序中调用,自然不会有输出。

4. 构建缓存或环境问题

  • 执行dotnet clean删除项目的bin和obj文件夹,再重新执行dotnet build && dotnet run,避免构建缓存导致生成器未重新运行。
  • 你的.NET 7 SDK版本(7.0.120)完全支持Source Generator,Host版本为8.0不影响编译过程,无需调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:35:10