C# Source Generators 翻译中文代码生成器,目前还是预览状态,没有正式推出,这玩意有什么用呢,下面介绍一下

在编译器期间 把特定的字符串代码编译 和 原有的代码进行集成,是反射,IL编织,MSBuild 任务处理 的另一种形似的加强版本。
以下是 集成器大致的要求 , 需要一个Generator特性,以及实现ISourceGenerator接口的一个类
namespace MyGenerator
{
[Generator]
public class MySourceGenerator : ISourceGenerator
{
public void Execute(SourceGeneratorContext context)
{
// TODO - actual source generator goes here!
}
public void Initialize(InitializationContext context)
{
// No initialization required for this one
}
}
}
具体的使用例子 ,这里想用在编译期间增加一个类HelloWorld,以及一些方法
namespace SourceGeneratorSamples
{
[Generator]
public class HelloWorldGenerator : ISourceGenerator
{
public void Execute(SourceGeneratorContext context)
{
// begin creating the source we'll inject into the users compilation
var sourceBuilder = new StringBuilder(@"
using System;
namespace HelloWorldGenerated
{
public static class HelloWorld
{
public static void SayHello()
{
Console.WriteLine(""Hello from generated code!"");
Console.WriteLine(""The following syntax trees existed in the compilation that created this program:"");
");
// using the context, get a list of syntax trees in the users compilation
var syntaxTrees = context.Compilation.SyntaxTrees;
// add the filepath of each tree to the class we're building
foreach (SyntaxTree tree in syntaxTrees)
{
sourceBuilder.AppendLine($@"Console.WriteLine(@"" - {tree.FilePath}"");");
}
// finish creating the source to inject
sourceBuilder.Append(@"
}
}
}");
// inject the created source into the users compilation
context.AddSource("helloWorldGenerator", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}
public void Initialize(InitializationContext context)
{
// No initialization required for this one
}
}
}
这里是具体的调用,当然这里的HelloWorld的识别依赖vs 的自能识别
public class SomeClassInMyCode
{
public void SomeMethodIHave()
{
HelloWorldGenerated.HelloWorld.SayHello(); // calls Console.WriteLine("Hello World!") and then prints out syntax trees
}
}
大概有什么用呢,目前官方是把它当做工具来用,用来做类似分析器 debug之类,代码生成。当然主要是预览版,后续肯定会增加功能。说下个人观点,这个功能其实是非常强大的,作为反射,IL编织的加强,自然可以联想到它的用途,比如AspNetCore缺少官方aop拦截,反射比较耗时等,使用该代码生成器可以在编译期间就能发现处理特定业务而非运行时,当然官方目前也紧把它作为反射的加强而非替代。 微软打算到c# 9.0正式推出,当然也要看功能稳定情况,而非必然。目前比较不爽的是,要手动写字符串的代码,这不是在开玩笑吗,写错代码怎么办,都发现不了 2333.
C#预览版引入了SourceGenerators,一种在编译期注入代码的强大工具,可增强反射和IL编织功能,用于代码生成和分析。本文通过实例展示了如何在编译时动态创建类和方法。

被折叠的 条评论
为什么被折叠?



