Edit3:在某些时候,这才开始起作用。不知道为什么。也许这是一个修复的VS错误?
Edit2:查看解决方案资源管理器中的 Analyzers 节点,我发现源生成器在我第一次打开程序时成功运行,然后它停止并且它生成的所有内容在对我的代码进行一些更改后就消失了。
immediately after opening solution:
> Analyzers
>> MySourceGenerators
>>> MySourceGenerators.NotifyPropertyChangesGenerator
>>>> _NotifyChangedClass_Notify.cs
after making any edits
> Analyzers
>> MySourceGenerators
>>> MySourceGenerators.NotifyPropertyChangesGenerator
>>>> This generator is not generating files.
编辑:按照评论的建议调用后Debugger.Launch()
,我可以确认生成器代码正在运行,并且源文本看起来与预期的完全一样。但是 IDE 和编译器仍然会出现错误,就好像没有包含结果一样。
我正在尝试设置一个源生成器以从本地项目引用运行,但无法使其实际运行。我的 NUnit 测试通过了,所以我知道实际的生成逻辑很好,但是准系统测试项目在 Visual Studio 中都无法编译并报告错误。我正在使用 Visual Studio 2022 Preview 5.0,以防万一。
<--generator.csproj-->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>10</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IncludeBuildOutpout>false</IncludeBuildOutpout>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" />
</ItemGroup>
</Project>
<--testproject.csproj-->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\MySourceGenerators\MySourceGenerators.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false"/>
</ItemGroup>
</Project>
//generator.cs
[Generator]
public class NotifyPropertyChangesGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
var receiver = (NotifySyntaxReceiver)context.SyntaxReceiver!;
if (receiver.Classes.Count > 0)
{
foreach (var c in receiver.Classes)
{
/* Generate the source */
var source = SyntaxFactory.ParseCompilationUnit(builder.ToString())
.NormalizeWhitespace()
.GetText(Encoding.UTF8, Microsoft.CodeAnalysis.Text.SourceHashAlgorithm.Sha256);
context.AddSource($"_{c.ClassDeclaration.Identifier.ValueText}_Notify", source);
}
}
}
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new NotifySyntaxReceiver());
}
}
class NotifySyntaxReceiver : ISyntaxReceiver
{
public List<NotifyClass> Classes { get; } = new();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax cds)
{
/* Identify classes that need generation */
}
}
}
//testproject.cs
internal class NotifyChangedClass : INotifyPropertyChanged
{
string n_Property;
}