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

C# 源生成器(Source Generators)是 .NET 5+ 引入的一项编译时功能,属于 Roslyn 编译器扩展的一部分。它允许你在编译过程中自动生成 C# 代码,从而减少重复的模板代码,比如属性通知、序列化逻辑、接口实现等。生成的代码在编译期间插入到项目中,对运行时性能没有影响,同时还能被调试器识别。
很多开发场景下需要写大量结构相似的代码,例如:
这些都可以通过源生成器在编译时自动完成,开发者只需关注核心逻辑。
下面以一个简化版的 INotifyPropertyChanged 自动生成为例,展示如何创建一个源生成器来减少模板代码。
步骤 1:创建源生成器项目
新建一个 .NET 类库项目,并修改 .csproj 文件,使其支持源生成器:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
</ItemGroup>
</Project>步骤 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<ClassDeclarationSyntax>()
.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 的代码。
编写源生成器时注意以下几点:
基本上就这些。源生成器不是魔法,但它能显著提升开发效率,尤其适合框架作者或需要大量样板代码的场景。
以上就是.NET中的C#源生成器(Source Generators)是什么?如何编写一个来减少模板代码?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号