源生成器能减少重复代码,如自动实现INotifyPropertyChanged;通过创建实现ISourceGenerator的类,在编译时生成部分类代码,结合属性标记和语法树分析,为标记的类自动生成通知逻辑,提升开发效率。

C# 源生成器(Source Generators)是 .NET 5+ 引入的一项编译时功能,属于 Roslyn 编译器扩展的一部分。它允许你在编译过程中自动生成 C# 代码,从而减少重复的模板代码,比如属性通知、序列化逻辑、接口实现等。生成的代码在编译期间插入到项目中,对运行时性能没有影响,同时还能被调试器识别。
源生成器能解决什么问题?
很多开发场景下需要写大量结构相似的代码,例如:
- INotifyPropertyChanged 接口实现用于 WPF 数据绑定
- 为记录类型生成深拷贝或比较方法
- 为枚举生成 JSON 序列化转换器
- 根据接口自动生成代理类或工厂代码
这些都可以通过源生成器在编译时自动完成,开发者只需关注核心逻辑。
如何编写一个简单的源生成器?
下面以一个简化版的 INotifyPropertyChanged 自动生成为例,展示如何创建一个源生成器来减少模板代码。
步骤 1:创建源生成器项目
新建一个 .NET 类库项目,并修改 .csproj 文件,使其支持源生成器:
netstandard2.0 latest
步骤 2:实现源生成器
创建一个类并实现 ISourceGenerator 接口:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text;
[Generator]
public class NotifyPropertyChangedGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context) { }
public void Execute(GeneratorExecutionContext context)
{
// 查找标记了特定属性的类
var classes = context.Compilation.SyntaxTrees
.SelectMany(tree => tree.GetRoot().DescendantNodes())
.OfType()
.Where(m => m.AttributeLists.SelectMany(a => a.Attributes)
.Any(attr => attr.Name.ToString() == "NotifyPropertyChanged"));
foreach (var cls in classes)
{
var namespaceName = GetNamespace(cls);
var className = cls.Identifier.Text;
var source = GenerateNotifyClass(namespaceName, className);
context.AddSource($"{className}.g.cs", SourceText.From(source, Encoding.UTF8));
}
}
private static string GetNamespace(ClassDeclarationSyntax classDecl)
{
SyntaxNode potentialNamespaceParent = classDecl.Parent;
while (potentialNamespaceParent != null &&
potentialNamespaceParent is not NamespaceDeclarationSyntax)
{
potentialNamespaceParent = potentialNamespaceParent.Parent;
}
return potentialNamespaceParent is NamespaceDeclarationSyntax ns ? ns.Name.ToString() : "Generated";
}
private static string GenerateNotifyClass(string ns, string className)
{
return $@"
namespace {ns}
{{
partial class {className} : System.ComponentModel.INotifyPropertyChanged
{{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
{{
PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}}
// 示例:你可以进一步生成属性包装器
}}
}}";
}
} 步骤 3:在目标项目中使用
在另一个项目中引用这个源生成器(可打包为 NuGet 或项目引用),然后使用:
[NotifyPropertyChanged]
public partial class Person
{
// 源生成器会自动让此类实现 INotifyPropertyChanged
// 你可以在子类或手动部分类中调用 OnPropertyChanged
}编译时,生成器会自动为 Person 类生成实现 INotifyPropertyChanged 的代码。
实用建议与注意事项
编写源生成器时注意以下几点:
- 使用 partial class 是关键,这样生成的代码可以和用户写的代码合并
- 避免生成过于复杂的逻辑,保持可读性和可调试性
- 利用 Microsoft.CodeAnalysis.CSharp.Syntax 构建语法树更安全,但字符串拼接简单场景够用
- 可通过 context.ReportDiagnostic 报告警告或错误
- 调试源生成器可用 Debugger.Launch() 或集成测试项目
基本上就这些。源生成器不是魔法,但它能显著提升开发效率,尤其适合框架作者或需要大量样板代码的场景。










