简体   繁体   English

.NET 5 源发生器是什么?

[英]What are the .NET 5 Source generators?

I see more and more open source libraries using .NET 5's Source Generators which improves their performance.我看到越来越多的开源库使用 .NET 5 的源代码生成器来提高它们的性能。

As much as I can understand from the docs , they are meant to replace System.Reflection becomes it comes at the expense of performance.据我从文档中了解到的,它们旨在取代System.Reflection成为它以牺牲性能为代价。 Is that true?真的吗? What I personally know about source generators is that when they introduced them in .NET 5, they were meant to generate C# code based on the.proto data contract files.我个人对源代码生成器的了解是,当他们在 .NET 5 引入它们时,它们的目的是根据 .proto 数据合同文件生成 C# 代码。

There is a clone library of MediatR which uses Source Generators instead of System.Reflection .有一个 MediatR 的克隆库,它使用 Source Generators 而不是System.Reflection

Could you simplify the source generators benefits and usage in that MediatR library and overall?您能否简化MediatR 库和整体中源代码生成器的好处和使用?

Source generators are really nothing magic - it's just some custom piece of code that generates text into files, which then get inserted into the compilation process and becomes part of the binary output (eg DLL or EXE) as if it was manually typed in by hand in some source file before you hit compile.源代码生成器真的没什么神奇的——它只是一些自定义代码,将文本生成到文件中,然后将其插入编译过程并成为二进制文件 output(例如 DLL 或 EXE)的一部分,就好像它是手动输入的一样在你点击编译之前在一些源文件中。

The only "magic" here is the formalized concept of analyzers-as-generators, which enables Visual Studio to automatically pass in the original source code into your custom generator routine and include the output whenever you build your project.这里唯一的“魔法”是分析器作为生成器的形式化概念,它使 Visual Studio 能够自动将原始源代码传递到您的自定义生成器例程中,并在您构建项目时包含 output。

One application of source generators is to create specialized, type-specific code for some operation that otherwise would require run-time reflection.源代码生成器的一个应用是为某些需要运行时反射的操作创建专门的、类型特定的代码。 Run-time reflection is typically rather slow and CPU intensive, yet often needed in order to centralize logic for common operations on unknown objects.运行时反射通常相当缓慢且占用大量 CPU,但通常需要它来集中对未知对象进行常见操作的逻辑。 A common example is the serialization and deserialization of objects.一个常见的例子是对象的序列化和反序列化。 This could be done either through reflection (lookup properties at run-time, invoke the getters and setters, etc) or through faster, type specific code that directly references properties and reads/writes to and from data streams.这可以通过反射(在运行时查找属性、调用 getter 和 setter 等)或通过更快、类型特定的代码直接引用属性和读取/写入数据流来完成。 However, creating such specialized code for every type is a lot of boring, repetitive work and so - enter source generators.然而,为每种类型创建这样的专用代码是一项非常枯燥、重复的工作,因此请输入源代码生成器。 They can do the "reflection" during build time and output slim, fast code into temporary.cs files, which get compiled with the product.他们可以在构建期间进行“反射”,并将 output 苗条、快速的代码转换为临时.cs 文件,这些文件与产品一起编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM