当使用 C# 源生成器时,会发现 ISourceGenerator 已经过时,是时候使用新版的 IIncrementalGenerator 了,以下为基本使用方法,以及 .csproj 的配置。
假如我们有以下项目结构:
Example/Example.csproj
Example.sln
要实现对 Example.csproj 进行代码生成,我们需要新建一个专门用于生成代码的子项目,类型为 Class Library,在此案例中为 Example.SourceGen.csproj:
Example/Example.csproj
Example.SourceGen/Example.SourceGen.csproj
Example.sln
以下为 Example.SourceGen.csproj 最简配置:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>13</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="5.0.0-1.25277.114">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" PrivateAssets="all" />
</ItemGroup>
</Project>
注意,这几乎是最简配置,功能如下:
<TargetFramework>netstandard2.0</TargetFramework> 源生成器要求必须使用,详见 https://github.com/dotnet/roslyn/blob/main/docs/roslyn-analyzers/rules/RS1041.md<LangVersion>13</LangVersion> 在 Example.SourceGen.csproj 项目中,使用默认的古老 C# 版本显然是不够的,因此我们可以单独设置语言版本<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> 必要选项<IsRoslynComponent>true</IsRoslynComponent> 必要选项Microsoft.CodeAnalysis.Analyzers 和 Microsoft.CodeAnalysis.CSharp 子项目至少需要包含这两个包接着在主项目中引用子项目即可:
<ItemGroup>
<ProjectReference Include="../Example.SourceGen/Example.SourceGen.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
然后就大功告成了,我们可以在子项目中创建一个 Gen.cs 然后开始编写我们的生成器代码了:
// Gen.cs under Example.SourceGen/Example.SourceGen.csproj
[Generator]
public class ScriptRegisterGen : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// code here
context.RegisterSourceOutput(classNames, (ctx, names) =>
{
// code here
ctx.AddSource("xxx.g.cs", source);
});
}
}