From 9c32fc1d9bff6668017776b26bcff8f347ff3157 Mon Sep 17 00:00:00 2001 From: lingdar77 Date: Fri, 3 Oct 2025 20:08:33 +0800 Subject: [PATCH] 3 --- Generator/MySourceGenerator.cs | 15 +++++---------- Source/Source.csproj | 2 ++ Source/templates/HelloWorld.template.cs | 7 +++++++ 3 files changed, 14 insertions(+), 10 deletions(-) create mode 100644 Source/templates/HelloWorld.template.cs diff --git a/Generator/MySourceGenerator.cs b/Generator/MySourceGenerator.cs index 5d9fef6..56c67cf 100644 --- a/Generator/MySourceGenerator.cs +++ b/Generator/MySourceGenerator.cs @@ -6,16 +6,11 @@ namespace MySourceGenerator { [Generator] public class MySourceGenerator : ISourceGenerator { public void Execute(GeneratorExecutionContext context) { - var sb = new StringBuilder(); - sb.AppendLine("using System;"); - sb.AppendLine("namespace Generated;"); - sb.AppendLine("public static class HelloWorld {"); - sb.AppendLine(" public static string SayHello() {"); - sb.AppendLine(" return \"Hello World!!!\";"); - sb.AppendLine(" }"); - sb.AppendLine("}"); - - context.AddSource("HelleWorld.generated", SourceText.From(sb.ToString(), Encoding.UTF8)); + var template = context.AdditionalFiles.Where(static file => file.Path.EndsWith("HelloWorld.template.cs")).First().GetText()?.ToString(); + if (template == null) { + return; + } + context.AddSource("HelleWorld.generated", SourceText.From(template, Encoding.UTF8)); } public void Initialize(GeneratorInitializationContext context) { diff --git a/Source/Source.csproj b/Source/Source.csproj index 95232ef..e60778d 100644 --- a/Source/Source.csproj +++ b/Source/Source.csproj @@ -6,6 +6,8 @@ + + diff --git a/Source/templates/HelloWorld.template.cs b/Source/templates/HelloWorld.template.cs new file mode 100644 index 0000000..6558b05 --- /dev/null +++ b/Source/templates/HelloWorld.template.cs @@ -0,0 +1,7 @@ +namespace Generated; + +public static class HelloWorld { + public static string SayHello() { + return "Hello World!!!"; + } +}