RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
C# 9 新特性:代码生成器、编译时反射

前言

今天 .NET 官方博客宣布 C# 9 Source Generators 第一个预览版发布,这是一个用户已经喊了快 5 年特性,今天终于发布了。

10年积累的网站设计、做网站经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站策划后付款的网站建设流程,更有荥阳免费网站建设让你可以放心的选择与我们合作。

简介

Source Generators 顾名思义代码生成器,它允许开发者在代码编译过程中获取查看用户代码并且生成新的 C# 代码参与编译过程,并且可以很好的与代码分析器集成提供 Intellisense、调试信息和报错信息,可以用它来做代码生成,因此也相当于是一个加强版本的编译时反射。

使用 Source Generators,可以做到这些事情:

  • 获取一个 Compilation 对象,这个对象表示了所有正在编译的用户代码,你可以从中获取 AST 和语义模型等信息
  • 可以向 Compilation 对象中插入新的代码,让编译器连同已有的用户代码一起编译

Source Generators 作为编译过程中的一个阶段执行:

编译运行 -> [分析源代码 -> 生成新代码] -> 将生成的新代码添加入编译过程 -> 编译继续。

上述流程中,中括号包括的内容即为 Source Generators 所参与的阶段和能做到的事情。

作用

.NET 明明具备运行时反射和动态 IL 织入功能,那这个 Source Generators 有什么用呢?

编译时反射 - 0 运行时开销

拿 ASP.NET Core 举例,启动一个 ASP.NET Core 应用时,首先会通过运行时反射来发现 Controllers、Services 等的类型定义,然后在请求管道中需要通过运行时反射获取其构造函数信息以便于进行依赖注入。然而运行时反射开销很大,即使缓存了类型签名,对于刚刚启动后的应用也无任何帮助作用,而且不利于做 AOT 编译。

Source Generators 将可以让 ASP.NET Core 所有的类型发现、依赖注入等在编译时就全部完成并编译到最终的程序集当中,最终做到 0 运行时反射使用,不仅利于 AOT 编译,而且运行时 0 开销。

除了上述作用之外,gRPC 等也可以利用此功能在编译时织入代码参与编译,不需要再利用任何的 MSBuild Task 做代码生成啦!

另外,甚至还可以读取 XML、JSON 直接生成 C# 代码参与编译,DTO 编写全自动化都是没问题的。

AOT 编译

Source Generators 的另一个作用是可以帮助消除 AOT 编译优化的主要障碍。

许多框架和库都大量使用反射,例如System.Text.Json、System.Text.RegularExpressions、ASP.NET Core 和 WPF 等等,它们在运行时从用户代码中发现类型。这些非常不利于 AOT 编译优化,因为为了使反射能够正常工作,必须将大量额外甚至可能不需要的类型元数据编译到最终的原生映像当中。

有了 Source Generators 之后,只需要做编译时代码生成便可以避免大部分的运行时反射的使用,让 AOT 编译优化工具能够更好的运行。

例子

INotifyPropertyChanged

写过 WPF 或 UWP 的都知道,在 ViewModel 中为了使属性变更可被发现,需要实现 INotifyPropertyChanged 接口,并且在每一个需要的属性的 setter 处除法属性更改事件:

 
 
 
  1. class MyViewModel : INotifyPropertyChanged 
  2. { 
  3. public event PropertyChangedEventHandler? PropertyChanged; 
  4.  
  5. private string _text; 
  6. public string Text 
  7. { 
  8. get => _text; 
  9. set 
  10. { 
  11. _text = value; 
  12. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text))); 
  13. } 
  14. } 
  15. } 

当属性多了之后将会非常繁琐,先前 C# 引入了 CallerMemberName 用于简化属性较多时候的情况:

 
 
 
  1. class MyViewModel : INotifyPropertyChanged 
  2. { 
  3. public event PropertyChangedEventHandler? PropertyChanged; 
  4.  
  5. private string _text; 
  6. public string Text 
  7. { 
  8. get => _text; 
  9. set 
  10. { 
  11. _text = value; 
  12. OnPropertyChanged(); 
  13. } 
  14. } 
  15.  
  16. protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) 
  17. { 
  18. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
  19. } 
  20. } 

即,用 CallerMemberName 指示参数,在编译时自动填充调用方的成员名称。

但是还是不方便。

如今有了 Source Generators,我们可以在编译时生成代码做到这一点了。

为了实现 Source Generators,我们需要写个实现了 ISourceGenerator 并且标注了 Generator的类型。

完整的 Source Generators 代码如下:

 
 
 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. using Microsoft.CodeAnalysis; 
  6. using Microsoft.CodeAnalysis.CSharp; 
  7. using Microsoft.CodeAnalysis.CSharp.Syntax; 
  8. using Microsoft.CodeAnalysis.Text; 
  9.  
  10. namespace MySourceGenerator 
  11. { 
  12. [Generator] 
  13. public class AutoNotifyGenerator : ISourceGenerator 
  14. { 
  15. private const string attributeText = @" 
  16. using System; 
  17. namespace AutoNotify 
  18. { 
  19. [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)] 
  20. sealed class AutoNotifyAttribute : Attribute 
  21. { 
  22. public AutoNotifyAttribute() 
  23. { 
  24. } 
  25. public string PropertyName { get; set; } 
  26. } 
  27. } 
  28. "; 
  29.  
  30. public void Initialize(InitializationContext context) 
  31. { 
  32. // 注册一个语法接收器,会在每次生成时被创建 
  33. context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); 
  34. } 
  35.  
  36. public void Execute(SourceGeneratorContext context) 
  37. { 
  38. // 添加 Attrbite 文本 
  39. context.AddSource("AutoNotifyAttribute", SourceText.From(attributeText, Encoding.UTF8)); 
  40.  
  41. // 获取先前的语法接收器  
  42. if (!(context.SyntaxReceiver is SyntaxReceiver receiver)) 
  43. return; 
  44.  
  45. // 创建处目标名称的属性 
  46. CSharpParseOptions options = (context.Compilation as CSharpCompilation).SyntaxTrees[0].Options as CSharpParseOptions; 
  47. Compilation compilation = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(attributeText, Encoding.UTF8), options)); 
  48.  
  49. // 获取新绑定的 Attribute,并获取INotifyPropertyChanged 
  50. INamedTypeSymbol attributeSymbol = compilation.GetTypeByMetadataName("AutoNotify.AutoNotifyAttribute"); 
  51. INamedTypeSymbol notifySymbol = compilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged"); 
  52.  
  53. // 遍历字段,只保留有 AutoNotify 标注的字段 
  54. List fieldSymbols = new List(); 
  55. foreach (FieldDeclarationSyntax field in receiver.CandidateFields) 
  56. { 
  57. SemanticModel model = compilation.GetSemanticModel(field.SyntaxTree); 
  58. foreach (VariableDeclaratorSyntax variable in field.Declaration.Variables) 
  59. { 
  60. // 获取字段符号信息,如果有 AutoNotify 标注则保存 
  61. IFieldSymbol fieldSymbol = model.GetDeclaredSymbol(variable) as IFieldSymbol; 
  62. if (fieldSymbol.GetAttributes().Any(ad => ad.AttributeClass.Equals(attributeSymbol, SymbolEqualityComparer.Default))) 
  63. { 
  64. fieldSymbols.Add(fieldSymbol); 
  65. } 
  66. } 
  67. } 
  68.  
  69. // 按 class 对字段进行分组,并生成代码 
  70. foreach (IGrouping group in fieldSymbols.GroupBy(f => f.ContainingType)) 
  71. { 
  72. string classSource = ProcessClass(group.Key, group.ToList(), attributeSymbol, notifySymbol, context); 
  73. context.AddSource($"{group.Key.Name}_autoNotify.cs", SourceText.From(classSource, Encoding.UTF8)); 
  74. } 
  75. } 
  76.  
  77. private string ProcessClass(INamedTypeSymbol classSymbol, List fields, ISymbol attributeSymbol, ISymbol notifySymbol, SourceGeneratorContext context) 
  78. { 
  79. if (!classSymbol.ContainingSymbol.Equals(classSymbol.ContainingNamespace, SymbolEqualityComparer.Default)) 
  80. { 
  81. // TODO: 必须在顶层,产生诊断信息 
  82. return null; 
  83. } 
  84.  
  85. string namespaceName = classSymbol.ContainingNamespace.ToDisplayString(); 
  86.  
  87. // 开始构建要生成的代码 
  88. StringBuilder source = new StringBuilder($@" 
  89. namespace {namespaceName} 
  90. {{ 
  91. public partial class {classSymbol.Name} : {notifySymbol.ToDisplayString()} 
  92. {{ 
  93. "); 
  94.  
  95. // 如果类型还没有实现 INotifyPropertyChanged 则添加实现 
  96. if (!classSymbol.Interfaces.Contains(notifySymbol)) 
  97. { 
  98. source.Append("public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;"); 
  99. } 
  100.  
  101. // 生成属性 
  102. foreach (IFieldSymbol fieldSymbol in fields) 
  103. { 
  104. ProcessField(source, fieldSymbol, attributeSymbol); 
  105. } 
  106.  
  107. source.Append("} }"); 
  108. return source.ToString(); 
  109. } 
  110.  
  111. private void ProcessField(StringBuilder source, IFieldSymbol fieldSymbol, ISymbol attributeSymbol) 
  112. { 
  113. // 获取字段名称 
  114. string fieldName = fieldSymbol.Name; 
  115. ITypeSymbol fieldType = fieldSymbol.Type; 
  116.  
  117. // 获取 AutoNotify Attribute 和相关的数据 
  118. AttributeData attributeData = fieldSymbol.GetAttributes().Single(ad => ad.AttributeClass.Equals(attributeSymbol, SymbolEqualityComparer.Default)); 
  119. TypedConstant overridenNameOpt = attributeData.NamedArguments.SingleOrDefault(kvp => kvp.Key == "PropertyName").Value; 
  120.  
  121. string propertyName = chooseName(fieldName, overridenNameOpt); 
  122. if (propertyName.Length == 0 || propertyName == fieldName) 
  123. { 
  124. //TODO: 无法处理,产生诊断信息 
  125. return; 
  126. } 
  127.  
  128. source.Append($@" 
  129. public {fieldType} {propertyName}  
  130. {{ 
  131. get  
  132. {{ 
  133. return this.{fieldName}; 
  134. }} 
  135. set 
  136. {{ 
  137. this.{fieldName} = value; 
  138. this.PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(nameof({propertyName}))); 
  139. }} 
  140. }} 
  141. "); 
  142.  
  143. string chooseName(string fieldName, TypedConstant overridenNameOpt) 
  144. { 
  145. if (!overridenNameOpt.IsNull) 
  146. { 
  147. return overridenNameOpt.Value.ToString(); 
  148. } 
  149.  
  150. fieldName = fieldName.TrimStart('_'); 
  151. if (fieldName.Length == 0) 
  152. return string.Empty; 
  153.  
  154. if (fieldName.Length == 1) 
  155. return fieldName.ToUpper(); 
  156.  
  157. return fieldName.Substring(0, 1).ToUpper() + fieldName.Substring(1); 
  158. } 
  159.  
  160. } 
  161.  
  162. // 语法接收器,将在每次生成代码时被按需创建 
  163. class SyntaxReceiver : ISyntaxReceiver 
  164. { 
  165. public List CandidateFields { get; } = new List(); 
  166.  
  167. // 编译中在访问每个语法节点时被调用,我们可以检查节点并保存任何对生成有用的信息 
  168. public void OnVisitSyntaxNode(SyntaxNode syntaxNode) 
  169. { 
  170. // 将具有至少一个 Attribute 的任何字段作为候选 
  171. if (syntaxNode is FieldDeclarationSyntax fieldDeclarationSyntax 
  172. && fieldDeclarationSyntax.AttributeLists.Count > 0) 
  173. { 
  174. CandidateFields.Add(fieldDeclarationSyntax); 
  175. } 
  176. } 
  177. } 
  178. } 
  179. } 

有了上述代码生成器之后,以后我们只需要这样写 ViewModel 就会自动生成通知接口的事件触发调用:

 
 
 
  1. public partial class MyViewModel 
  2. { 
  3. [AutoNotify] 
  4. private string _text = "private field text"; 
  5.  
  6. [AutoNotify(PropertyName = "Count")] 
  7. private int _amount = 5; 
  8. } 

上述代码将会在编译时自动生成以下代码参与编译:

 
 
 
  1. public partial class MyViewModel : System.ComponentModel.INotifyPropertyChanged 
  2. { 
  3. public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 
  4.  
  5. public string Text 
  6. { 
  7. get  
  8. { 
  9. return this._text; 
  10. } 
  11. set 
  12. { 
  13. this._text = value; 
  14. this.PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(nameof(Text))); 
  15. } 
  16. } 
  17.  
  18. public int Count 
  19. { 
  20. get  
  21. { 
  22. return this._amount; 
  23. } 
  24. set 
  25. { 
  26. this._amount = value; 
  27. this.PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(nameof(Count))); 
  28. } 
  29. } 
  30. } 

非常方便!

使用时,将 Source Generators 部分作为一个独立的 .NET Standard 2.0 程序集(暂时不支持 2.1),用以下方式引入到你的项目即可:

 
 
 
  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  

注意需要 .NET 5 preview 3 或以上版本,并指定语言版本为 preview :

 
 
 
  1.  
  2. preview 
  3.  

另外,Source Generators 需要引入两个 nuget 包:

 
 
 
  1.  
  2.  
  3.  
  4.  

限制

Source Generators 仅能用于访问和生成代码,但是不能修改已有代码,这有一定原因是出于安全考量。

文档

Source Generators 处于早期预览阶段,docs.microsoft.com 上暂时没有相关文档,关于它的文档请访问在 roslyn 仓库中的文档:

设计文档

使用文档

后记

目前 Source Generators 仍处于非常早期的预览阶段,API 后期还可能会有很大的改动,因此现阶段不要用于生产。

另外,关于与 IDE 的集成、诊断信息、断点调试信息等的开发也在进行中,请期待后续的 preview 版本吧。


网站栏目:C# 9 新特性:代码生成器、编译时反射
分享链接:http://pengzhouwz.cn/article/cojepog.html