From 73c474c37a7c79c9c3229f0eb54a7a0a6b277dc3 Mon Sep 17 00:00:00 2001 From: GeWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Wed, 24 Dec 2025 12:57:26 +0800 Subject: [PATCH] =?UTF-8?q?fix(generator):=20=E4=BF=AE=E5=A4=8D=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E7=94=9F=E6=88=90=E5=99=A8=E4=B8=AD=E7=9A=84=E8=AF=8A?= =?UTF-8?q?=E6=96=AD=E5=92=8C=E5=88=86=E7=B1=BB=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 使用预定义的 Diagnostics.MustBePartial 替代手动创建 DiagnosticDescriptor - 优化构造函数参数检查逻辑,添加对 null 值和无效类型的处理 - 增加三种参数情况的处理:null 值、有效字符串、无效类型 - 添加错误情况下的回退机制,使用默认分类值 - 改进代码注释和错误处理的健壮性 --- .../generator/logging/LoggerGenerator.cs | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/GFramework.Generator/generator/logging/LoggerGenerator.cs b/GFramework.Generator/generator/logging/LoggerGenerator.cs index c60da8b..34129f1 100644 --- a/GFramework.Generator/generator/logging/LoggerGenerator.cs +++ b/GFramework.Generator/generator/logging/LoggerGenerator.cs @@ -57,8 +57,7 @@ namespace GFramework.Generator.generator.logging { // 如果 Diagnostics 类有问题,这里可能会崩,先注释掉或确保该类存在 spc.ReportDiagnostic(Diagnostic.Create( - new DiagnosticDescriptor("GEN001", "Class must be partial", "Class '{0}' must be partial", - "Usage", DiagnosticSeverity.Error, true), + Diagnostics.MustBePartial, classDecl.Identifier.GetLocation(), classSymbol.Name)); @@ -102,16 +101,34 @@ namespace GFramework.Generator.generator.logging var className = classSymbol.Name; // === 解析 Category === - string category = className; // 默认值 + string category = className; // 默认使用类名 - // 检查构造函数参数 (第一个参数) + // 检查是否有构造函数参数 if (attr.ConstructorArguments.Length > 0) { var argValue = attr.ConstructorArguments[0].Value; - if (argValue is string s && !string.IsNullOrWhiteSpace(s)) + + // 情况 1: 参数存在,但值为 null (例如 [Log] 且构造函数有默认值 null) + if (argValue is null) + { + category = className; + } + // 情况 2: 参数存在,且是有效的字符串 (例如 [Log("MyCategory")]) + else if (argValue is string s && !string.IsNullOrWhiteSpace(s)) { category = s; } + // 情况 3: 参数存在,但类型不对 (防御性编程) + else + { + // 这里可以选择报错,或者回退到默认值。 + // 为了让用户知道写错了,保留报错逻辑是合理的。 + // 注意:这里需要你有 ReportDiagnostic 的逻辑,如果没有,为了不中断生成,建议回退到默认值。 + + // 如果你在 Generate 方法里无法轻松调用 ReportDiagnostic, + // 建议直接忽略错误使用默认值,或者生成一段 #error 代码。 + category = $"{className}_InvalidArg"; + } } // === 解析 Named Arguments (更加安全的获取方式) ===