Visual Studio 2022中Source Generator被忽略的问题求助
解决Source Generator被忽略的问题
1. 彻底清理项目缓存
- 删除源生成器项目(ClassLibrary1)和消费项目的
bin、obj文件夹 - 关闭Visual Studio,删除
%LOCALAPPDATA%\Microsoft\VisualStudio\<你的VS版本号>\ComponentModelCache目录 - 重启Visual Studio,重新构建整个解决方案
2. 验证源生成器项目的包配置
确保Microsoft.CodeAnalysis.CSharp包的配置正确,避免引用传递:
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" PrivateAssets="All" />
若版本兼容性存疑,可尝试更新到与Visual Studio 2022兼容的最新稳定版本(比如4.8.x系列)
3. 检查消费项目的引用配置
确认项目引用的属性无误,无拼写错误:
<ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
若同时引用了多个生成器项目(如DtoGenerator),可暂时移除其他引用,先单独测试ClassLibrary1是否能正常工作
4. 调试生成器是否被执行
在生成器类的Initialize方法中添加调试触发代码,验证生成器是否被加载:
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System; using System.Text; using System.Diagnostics; namespace ClassLibrary1 { [Generator] public class CustomGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { #if DEBUG Debugger.Launch(); // 触发调试器 #endif } public void Execute(GeneratorExecutionContext context) { context.AddSource("myGeneratedFile.cs", SourceText.From(@" namespace GeneratedNamespace { public class GeneratedClass { public static void GeneratedMethod() { // generated code } } }", Encoding.UTF8)); } } }
构建消费项目时,会弹出调试器选择窗口,选择当前Visual Studio实例,即可断点调试生成器的执行流程
5. 检查生成文件输出位置
在消费项目的项目文件中添加以下配置,强制输出生成的代码到指定目录,方便验证:
<PropertyGroup> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath> </PropertyGroup>
构建后查看消费项目根目录下的Generated文件夹,若存在myGeneratedFile.cs,说明生成器已工作,只需在代码中引用GeneratedNamespace.GeneratedClass即可使用
6. 尝试切换源生成器项目的目标框架
将ClassLibrary1的目标框架从netstandard2.1改为net7.0,避免跨框架兼容性问题:
<PropertyGroup> <TargetFramework>net7.0</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup>
内容的提问来源于stack exchange,提问作者Enrico
相关产品推荐
相关产品推荐

