- 必须创建 netstandard项目【ClassLibrary1】来存放代码生成接口
[Generator]
public class DemoSourceGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
// Find the main method
var mainMethod = context.Compilation.GetEntryPoint(context.CancellationToken);
// Build up the source code
string source = $@"// <auto-generated/>
using System;
namespace {mainMethod.ContainingNamespace.ToDisplayString()}
{{
public static partial class {mainMethod.ContainingType.Name}
{{
static partial void HelloFrom(string name) =>
Console.WriteLine($""Generator says: Hi from '{{name}}'"");
}}
}}
";
var typeName = mainMethod.ContainingType.Name;
// Add the source code to the compilation
context.AddSource($"{typeName}.g.cs", source);
}
public void Initialize(GeneratorInitializationContext context)
{
// No initialization required for this one
}
}
- 创建测试程序 - 控制台【ConsoleApp1】
partial class Program
{
static void Main(string[] args)
{
HelloFrom("Generated Code");
}
static partial void HelloFrom(string name);
}
- 配置【ConsoleApp1】添加 OutputItemType="Analyzer" ReferenceOutputAssembly="false"
![](/i/l/?n=23&i=blog/944369/202304/944369-20230404183201456-1511027424.png)
- 运行得到结果
![](/i/l/?n=23&i=blog/944369/202304/944369-20230404183247836-1993282203.png)
[参考]
源生成器
抽丝剥茧!Source Generators原理讲解