This commit is contained in:
2025-10-03 20:08:33 +08:00
parent c0157a7e91
commit 9c32fc1d9b
3 changed files with 14 additions and 10 deletions
+5 -10
View File
@@ -6,16 +6,11 @@ namespace MySourceGenerator {
[Generator] [Generator]
public class MySourceGenerator : ISourceGenerator { public class MySourceGenerator : ISourceGenerator {
public void Execute(GeneratorExecutionContext context) { public void Execute(GeneratorExecutionContext context) {
var sb = new StringBuilder(); var template = context.AdditionalFiles.Where(static file => file.Path.EndsWith("HelloWorld.template.cs")).First().GetText()?.ToString();
sb.AppendLine("using System;"); if (template == null) {
sb.AppendLine("namespace Generated;"); return;
sb.AppendLine("public static class HelloWorld {"); }
sb.AppendLine(" public static string SayHello() {"); context.AddSource("HelleWorld.generated", SourceText.From(template, Encoding.UTF8));
sb.AppendLine(" return \"Hello World!!!\";");
sb.AppendLine(" }");
sb.AppendLine("}");
context.AddSource("HelleWorld.generated", SourceText.From(sb.ToString(), Encoding.UTF8));
} }
public void Initialize(GeneratorInitializationContext context) { public void Initialize(GeneratorInitializationContext context) {
+2
View File
@@ -6,6 +6,8 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Generator\Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> <ProjectReference Include="..\Generator\Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<Compile Remove="*/*.template.cs" />
<AdditionalFiles Include="*/*.template.cs" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+7
View File
@@ -0,0 +1,7 @@
namespace Generated;
public static class HelloWorld {
public static string SayHello() {
return "Hello World!!!";
}
}