C# Source Generator未运行:按官方教程操作无输出问题排查
排查Source Generator无输出的常见问题
针对你按照官方教程实现Source Generator后控制台项目dotnet run无输出的情况,从以下几个核心环节排查:
1. 生成器项目配置是否正确
- 确认
TestSourceGenerator.csproj中包含以下关键配置:
Source Generator必须以<PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <IsRoslynComponent>true</IsRoslynComponent> </PropertyGroup>netstandard2.0为目标框架,且IsRoslynComponent设为true才能被Roslyn识别。 - 检查是否引用了正确的分析器包,需添加:
版本需与你的.NET 7 SDK兼容(4.x系列适配.NET 7)。<ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.6.0" PrivateAssets="all" /> <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" /> </ItemGroup>
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
相关产品推荐
相关产品推荐

