渭南网站建设费用明细,网页设计代码模板下载,开发工具都有哪些,网站建设详细合同范本前言前段时间#xff0c;我们已经用Source Generators实现了好多功能#xff0c;比如AutoMapper、API最佳实践。你看完那些实现代码#xff0c;是不是还有点云里雾里#xff01;Source Generators到底是怎么做到的#xff1f;基础知识Source Generators是编译过程的一部分… 前言前段时间我们已经用Source Generators实现了好多功能比如AutoMapper、API最佳实践。你看完那些实现代码是不是还有点云里雾里Source Generators到底是怎么做到的基础知识Source Generators是编译过程的一部分它以编译树作为输入通过分析代码动态生成文件并把它们加入到编译过程中需要注意的是你只能添加一些东西到代码但不能改变现有的代码。为了使用Source Generators你必须创建.Net Standard项目并引用nuget包Microsoft.CodeAnalysis.CSharp 3.8.0或以上版本。基本的实现代码如下你必须实现ISourceGenerator接口并且用GeneratorAttribute标注[Generator]
public class DemoSourceGenerator : ISourceGenerator
{public void Execute(GeneratorExecutionContext context){throw new NotImplementedException();}public void Initialize(GeneratorInitializationContext context){throw new NotImplementedException();}
}
生成器执行上下文主要生成过程通过Execute方法执行。Execute传递一个GeneratorExecutionContext实例下列是实例常用的属性和方法:AdditionalFiles 获取当前编译项目文件中的所有AdditionalFiles标签Compilation 编译上下文最重要的对象AddSource 向编译器加入代码最重要的方法语法树通过GeneratorExecutionContext.Compilation我们可以获得编译上下文有了这个对象你就可以访问当前编译项目的整个语法树SyntaxTree。那什么是语法树呢首先安装.NET Compiler Platform SDK。然后在VS中打开“视图”-“其他窗口”-“Syntax Visualizer”。可以看到语法树是一个树形结构和每一行代码一一对应语法树包含三种类型的项——node、token和trivia。比如public class Class1 { }整体是ClassDeclaration node,下级的Class1则是ClassKeyword token, 而紧跟的空格则是Whitespace trivia。因此只要我们遍历语法树即可拿到编译中的任何代码。Demo现在把上面的综合起来我们就可以开发Source Generators功能了public void Execute(GeneratorExecutionContext context)
{//获取第一个附加文件内容用作代码模板var template context.AdditionalFiles.First().GetText().ToString();//获取第一个类名var className context.Compilation.SyntaxTrees.SelectMany(p p.GetRoot().DescendantNodes().OfTypeClassDeclarationSyntax()).First().Identifier.Text;// 替换文本生成代码// 你也可以使用模板引擎或者StringBuilder拼接出代码var source template.Replace({Class}, className);// 向编译过程添加代码文件context.AddSource(Demo, SourceText.From(source, Encoding.UTF8));
}
在待编译的项目中添加一个附加文件ItemGroupAdditionalFiles Includetemplate.txt /
/ItemGroup
template.txt的文件内容如下using System;namespace ClassLibrary1
{public static class Demo{public static void SayHello(){Console.WriteLine(Hello {Class});}}
}
编译后可以看到生成如下代码:结论希望我已经描述清楚了使用Source Generators的整个过程。期待你用它开发出更多更好的功能如果你觉得这篇文章对你有所启发请关注我的个人公众号”My IO“记住我