返回提交历史
Modified
README.md
+38
-5
Modified
README.zh-CN.md
+38
-5
Modified
XFEExtension.NetCore.AutoConfig.Analyzer/AnalyzerReleases.Unshipped.md
+2
-0
Modified
XFEExtension.NetCore.AutoConfig.Analyzer/Diagnostics/AutoConfigDiagnostics.cs
+137
-1
Modified
XFEExtension.NetCore.AutoConfig.Analyzer/Generator/ProfilePropertyAutoGenerator.cs
+154
-62
Modified
XFEExtension.NetCore.AutoConfig.CodeFix/AutoConfigCodeFixProvider.cs
+182
-1
Modified
XFEExtension.NetCore.AutoConfig.Tests/GeneratorAndCodeFixTests.cs
+123
-2
Modified
XFEExtension.NetCore.AutoConfig.Tests/PersistenceProfiles.cs
+9
-0
Modified
XFEExtension.NetCore.AutoConfig.Tests/PersistenceTests.cs
+11
-0
Modified
XFEExtension.NetCore.AutoConfig/ProfilePropertyAddGetAttribute.cs
+1
-1
Modified
XFEExtension.NetCore.AutoConfig/ProfilePropertyAddSetAttribute.cs
+1
-1
Modified
XFEExtension.NetCore.AutoConfig/XFEExtension.NetCore.AutoConfig.csproj
+1
-0
XFEstudio/XFEExtension.NetCore.AutoConfig
支持 .NET 10 partial property 及相关特性扩展
新增对 .NET 10 / C# 14 partial property 的支持,允许在配置类中声明 public partial InstanceXxx { get; set; },生成器自动实现后备存储、同步和绑定,静态属性保持不变。 [ProfileProperty]、[ProfilePropertyAddGet]、[ProfilePropertyAddSet] 特性现可用于字段和 partial 属性,文档已同步。 分析器新增 XFE0003 诊断,检测可升级为 partial property 的字段,并提供自动迁移代码修复。 生成器支持 partial property,自动生成静态属性、序列化、同步和钩子方法,声明不规范时报 XFE1009。 单元测试覆盖生成、诊断、修复、序列化和升级场景。 文档补充 partial property 用法、升级建议和迁移示例。
0777545
代码差异
12 个文件
+697
-78
@@ -51,6 +51,39 @@ class Program
51
51
>
52
52
> Automatic saves are coalesced over a 100 ms window by default. A burst of assignments therefore produces one complete file write instead of one write per property. Call `SaveProfile()` when the current snapshot must be flushed immediately.
53
53
54
### .NET 10 Partial Properties
55
56
Projects targeting .NET 10 or later with C# 14 can declare partial instance properties for the generator to implement. The generated implementation uses `field` for backing storage, synchronization, and collection binding. The existing static `Name` facade is still generated, so profile call sites do not change:
57
58
```csharp
59
[AutoLoadProfile]
60
partial class SystemProfile : XFEProfile
61
{
62
[ProfileProperty]
63
public partial string InstanceName { get; set; } = string.Empty;
64
65
[ProfileProperty]
66
public partial int InstanceAge { get; set; }
67
}
68
69
SystemProfile.Name = "Test";
70
Console.WriteLine(SystemProfile.Age);
71
```
72
73
Partial profile properties must be named `InstanceXxx`; the persisted name and static facade remain `Xxx`. For example, `[ProfileProperty("DisplayName")]` maps to `InstanceDisplayName`, static `DisplayName`, and the XML element `<DisplayName>`.
74
75
The field syntax remains supported. In a .NET 10+ project using C# 14, analyzer diagnostic `XFE0003` suggests eligible fields and offers the “Convert to .NET 10 partial profile property” code fix. The fix preserves the initializer, updates field references and get/set hook strings, and retargets other field attributes with `field:`. The equivalent manual migration is:
76
77
```csharp
78
// Before
79
[ProfileProperty]
80
string name = "Guest";
81
82
// .NET 10 / C# 14
83
[ProfileProperty]
84
public partial string InstanceName { get; set; } = "Guest";
85
```
86
54
87
---
55
88
56
89
## Detailed Usage
@@ -415,9 +448,9 @@ This explicit policy prevents the sample or package metadata from implying an AO
415
448
416
449
| Attribute | Target | Description |
417
450
|-----------|--------|-------------|
418
| `[ProfileProperty]` | Field | Marks the field for code generation. Optionally specify a property name: `[ProfileProperty("CustomName")]` |
419
| `[ProfilePropertyAddGet(code)]` | Field | Appends a code line to the generated `get` accessor. Supports multiple attributes. |
420
| `[ProfilePropertyAddSet(code)]` | Field | Appends a code line to the generated `set` accessor. Supports multiple attributes. |
451
| `[ProfileProperty]` | Field or partial property | Marks the member for code generation. Optionally specify a property name: `[ProfileProperty("CustomName")]` |
452
| `[ProfilePropertyAddGet(code)]` | Field or partial property | Appends a code line to the generated `get` accessor. Supports multiple attributes. |
453
| `[ProfilePropertyAddSet(code)]` | Field or partial property | Appends a code line to the generated `set` accessor. Supports multiple attributes. |
421
454
| `[AutoLoadProfile(false)]` | Class | Keeps `Current` initialized but disables automatic file loading. |
422
455
| `[ProfilePath(path)]` | Class | Sets the storage path for the config file. |
423
456
@@ -449,8 +482,8 @@ For every `partial` class that inherits `XFEProfile` and uses `[ProfileProperty]
449
482
| `ExportProfileBytes()` | `static byte[]` | Exports raw config bytes; preferred for MessagePack |
450
483
| `ImportProfile(string)` | `static void` | Imports config from a string |
451
484
| `ImportProfileBytes(ReadOnlyMemory<byte>)` | `static void` | Imports config directly from bytes |
452
| `XxxProperty` (per field) | `static T` | Auto-generated static property; saves on set |
453
| `InstanceXxx` (per field) | `T` (instance) | Corresponding instance property |
485
| `Xxx` (per profile member) | `static T` | Auto-generated static property; saves on set |
486
| `InstanceXxx` (per profile member) | `T` (instance) | Corresponding instance property; may be user-declared as a partial property on .NET 10 |
454
487
| `GetXxxProperty()` | `static partial void` | Invoked when the property is read |
455
488
| `SetXxxProperty(ref T)` | `static partial void` | Invoked when the property is written |
456
489
@@ -51,6 +51,39 @@ class Program
51
51
>
52
52
> 自动保存默认会在 100ms 窗口内合并。同一批属性赋值只会完整写入一次文件,不再每次赋值都写入;需要立即落盘时可显式调用 `SaveProfile()`。
53
53
54
### .NET 10 部分属性
55
56
目标项目为 .NET 10 或更高版本并使用 C# 14 时,可以直接声明由生成器实现的部分实例属性。生成器会用 `field` 实现后备存储、并发锁与集合绑定,同时仍生成原有的静态 `Name` 属性,因此调用配置的方式不变:
57
58
```csharp
59
[AutoLoadProfile]
60
partial class SystemProfile : XFEProfile
61
{
62
[ProfileProperty]
63
public partial string InstanceName { get; set; } = string.Empty;
64
65
[ProfileProperty]
66
public partial int InstanceAge { get; set; }
67
}
68
69
SystemProfile.Name = "Test";
70
Console.WriteLine(SystemProfile.Age);
71
```
72
73
部分属性必须命名为 `InstanceXxx`;持久化名称和静态属性名仍为 `Xxx`。例如 `[ProfileProperty("DisplayName")]` 对应 `InstanceDisplayName`、静态 `DisplayName` 和 XML 节点 `<DisplayName>`。
74
75
旧的字段写法继续受到支持。对于目标为 .NET 10+ 且启用 C# 14 的项目,分析器会以 `XFE0003` 提示可升级字段,并提供“转换为 .NET 10 部分配置属性”代码修复。修复会保留初始值、更新字段引用和 get/set 特性中的字段名;原字段上的其他特性会改为 `field:` 目标。手动升级时可按以下方式转换:
76
77
```csharp
78
// 旧写法
79
[ProfileProperty]
80
string name = "Guest";
81
82
// .NET 10 / C# 14 写法
83
[ProfileProperty]
84
public partial string InstanceName { get; set; } = "Guest";
85
```
86
54
87
---
55
88
56
89
## 详细用法
@@ -408,9 +441,9 @@ SystemProfile.ImportProfile(exported); // 从字符串导入配置
408
441
409
442
| 特性 | 应用目标 | 说明 |
410
443
|------|----------|------|
411
| `[ProfileProperty]` | 字段 | 标记该字段参与自动生成,可指定属性名 `[ProfileProperty("CustomName")]` |
412
| `[ProfilePropertyAddGet(code)]` | 字段 | 在生成的 `get` 访问器中追加代码行,支持多个 |
413
| `[ProfilePropertyAddSet(code)]` | 字段 | 在生成的 `set` 访问器中追加代码行,支持多个 |
444
| `[ProfileProperty]` | 字段或部分属性 | 标记该成员参与自动生成,可指定属性名 `[ProfileProperty("CustomName")]` |
445
| `[ProfilePropertyAddGet(code)]` | 字段或部分属性 | 在生成的 `get` 访问器中追加代码行,支持多个 |
446
| `[ProfilePropertyAddSet(code)]` | 字段或部分属性 | 在生成的 `set` 访问器中追加代码行,支持多个 |
414
447
| `[AutoLoadProfile(false)]` | 类 | 保持 `Current` 已初始化,但禁用自动文件加载 |
415
448
| `[ProfilePath(path)]` | 类 | 指定配置文件存储路径 |
416
449
@@ -442,8 +475,8 @@ SystemProfile.ImportProfile(exported); // 从字符串导入配置
442
475
| `ExportProfileBytes()` | `static byte[]` | 直接导出配置字节,适合 MessagePack |
443
476
| `ImportProfile(string)` | `static void` | 从字符串导入配置 |
444
477
| `ImportProfileBytes(ReadOnlyMemory<byte>)` | `static void` | 直接从配置字节导入 |
445
| `XxxProperty`(每个字段)| `static T` | 自动生成的静态属性,读写时自动持久化 |
446
| `InstanceXxx`(每个字段)| `T`(实例)| 对应的实例属性 |
478
| `Xxx`(每个配置成员)| `static T` | 自动生成的静态属性,读写时自动持久化 |
479
| `InstanceXxx`(每个配置成员)| `T`(实例)| 对应的实例属性;.NET 10 下可由用户声明为部分属性 |
447
480
| `GetXxxProperty()` | `static partial void` | get 钩子分部方法 |
448
481
| `SetXxxProperty(ref T)` | `static partial void` | set 钩子分部方法 |
449
482
@@ -13,3 +13,5 @@ XFE1005 | XFEExtension.NetCore.AutoConfig.Generator | Error | Missing parameterl
13
13
XFE1006 | XFEExtension.NetCore.AutoConfig.Generator | Error | Reserved generated member conflict
14
14
XFE1007 | XFEExtension.NetCore.AutoConfig.Generator | Error | Unsupported profile field
15
15
XFE1008 | XFEExtension.NetCore.AutoConfig.Generator | Error | Profile type must inherit XFEProfile
16
XFE1009 | XFEExtension.NetCore.AutoConfig.Generator | Error | Unsupported partial profile property declaration
17
XFE0003 | XFEExtension.NetCore.AutoConfig.Diagnostics | Info | Profile field can be upgraded to a .NET 10 partial property
@@ -2,6 +2,7 @@ using Microsoft.CodeAnalysis;
2
2
using Microsoft.CodeAnalysis.CSharp;
3
3
using Microsoft.CodeAnalysis.CSharp.Syntax;
4
4
using Microsoft.CodeAnalysis.Diagnostics;
5
using System;
5
6
using System.Collections.Immutable;
6
7
using System.Linq;
7
8
using System.Text.RegularExpressions;
@@ -13,8 +14,12 @@ public sealed class AutoConfigDiagnostics : DiagnosticAnalyzer
13
14
{
14
15
private const string AddGetAttributeName = "XFEExtension.NetCore.AutoConfig.ProfilePropertyAddGetAttribute";
15
16
private const string AddSetAttributeName = "XFEExtension.NetCore.AutoConfig.ProfilePropertyAddSetAttribute";
17
private const string ProfilePropertyAttributeName = "XFEExtension.NetCore.AutoConfig.ProfilePropertyAttribute";
18
private const string ProfileBaseTypeName = "XFEExtension.NetCore.AutoConfig.XFEProfile";
19
private const string TargetFrameworkAttributeName = "System.Runtime.Versioning.TargetFrameworkAttribute";
16
20
17
21
public const string AddGetNoResultErrorId = "XFE0002";
22
public const string FieldCanUsePartialPropertyId = "XFE0003";
18
23
public const string AddSetNoSetResultWarningId = "XFW0001";
19
24
20
25
public static readonly DiagnosticDescriptor AddGetNoResultError = new(
@@ -37,13 +42,23 @@ public sealed class AutoConfigDiagnostics : DiagnosticAnalyzer
37
42
"设置了自定义的Set方法但是没有对实际字段进行操作.",
38
43
"https://www.xfegzs.com/Docs/View/Errors%2FAutoConfig%2FXFW0001");
39
44
40
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [AddGetNoResultError, AddSetNoSetResultWarning];
45
public static readonly DiagnosticDescriptor FieldCanUsePartialProperty = new(
46
FieldCanUsePartialPropertyId,
47
"配置字段可升级为部分属性",
48
"配置字段“{0}”可升级为 .NET 10 部分属性“{1}”,以减少显式字段和生成成员",
49
"XFEExtension.NetCore.AutoConfig.Diagnostics",
50
DiagnosticSeverity.Info,
51
true,
52
"目标项目为 .NET 10 或更高版本时,可使用 C# 14 field-backed partial property,并通过代码修复完成迁移.");
53
54
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [AddGetNoResultError, AddSetNoSetResultWarning, FieldCanUsePartialProperty];
41
55
42
56
public override void Initialize(AnalysisContext context)
43
57
{
44
58
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
45
59
context.EnableConcurrentExecution();
46
60
context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration);
61
context.RegisterSyntaxNodeAction(AnalyzePropertyDeclaration, SyntaxKind.PropertyDeclaration);
47
62
}
48
63
49
64
private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context)
@@ -62,14 +77,135 @@ public sealed class AutoConfigDiagnostics : DiagnosticAnalyzer
62
77
63
78
var setAttributes = field.GetAttributes().Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AddSetAttributeName).ToArray();
64
79
if (setAttributes.Length == 0)
80
{
81
ReportPartialPropertySuggestion(context, declaration, variable, field);
65
82
continue;
83
}
66
84
var assignmentPattern = $@"\b{Regex.Escape(field.Name)}\s*=\s*value\b";
67
85
if (!setAttributes.Select(GetCode).Any(code => code is not null && Regex.IsMatch(code, assignmentPattern)))
68
86
context.ReportDiagnostic(Diagnostic.Create(AddSetNoSetResultWarning, GetAttributeLocation(setAttributes[setAttributes.Length - 1], variable), field.Name));
87
ReportPartialPropertySuggestion(context, declaration, variable, field);
69
88
}
70
89
}
71
90
91
private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context)
92
{
93
var declaration = (PropertyDeclarationSyntax)context.Node;
94
if (context.SemanticModel.GetDeclaredSymbol(declaration, context.CancellationToken) is not IPropertySymbol property
95
|| !property.GetAttributes().Any(static attribute => attribute.AttributeClass?.ToDisplayString() == ProfilePropertyAttributeName))
96
return;
97
98
var getAttributes = property.GetAttributes().Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AddGetAttributeName).ToArray();
99
if (getAttributes.Length > 0 && !getAttributes.Select(GetCode).Any(static code => code?.Contains("return") == true))
100
context.ReportDiagnostic(Diagnostic.Create(AddGetNoResultError, GetAttributeLocation(getAttributes[getAttributes.Length - 1], declaration), property.Name));
101
102
var setAttributes = property.GetAttributes().Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AddSetAttributeName).ToArray();
103
if (setAttributes.Length == 0)
104
return;
105
var assignmentPattern = $@"\b{Regex.Escape(property.Name)}\s*=\s*value\b";
106
if (!setAttributes.Select(GetCode).Any(code => code is not null && Regex.IsMatch(code, assignmentPattern)))
107
context.ReportDiagnostic(Diagnostic.Create(AddSetNoSetResultWarning, GetAttributeLocation(setAttributes[setAttributes.Length - 1], declaration), property.Name));
108
}
109
110
private static void ReportPartialPropertySuggestion(SyntaxNodeAnalysisContext context, FieldDeclarationSyntax declaration, VariableDeclaratorSyntax variable, IFieldSymbol field)
111
{
112
if (declaration.Declaration.Variables.Count != 1
113
|| field.IsStatic
114
|| field.IsConst
115
|| field.IsReadOnly
116
|| field.IsFixedSizeBuffer
117
|| field.Type is IPointerTypeSymbol
118
|| field.Type is IFunctionPointerTypeSymbol
119
|| declaration.Modifiers.Any(SyntaxKind.VolatileKeyword)
120
|| declaration.Modifiers.Any(SyntaxKind.UnsafeKeyword)
121
|| !field.GetAttributes().Any(static attribute => attribute.AttributeClass?.ToDisplayString() == ProfilePropertyAttributeName)
122
|| !DerivesFromXfeProfile(field.ContainingType)
123
|| !SupportsNet10PartialProperties(context))
124
return;
125
126
var propertyName = GetGeneratedPropertyName(field);
127
if (string.IsNullOrWhiteSpace(propertyName)
128
|| !SyntaxFacts.IsValidIdentifier(propertyName)
129
|| SyntaxFacts.GetKeywordKind(propertyName) != SyntaxKind.None
130
|| SyntaxFacts.GetContextualKeywordKind(propertyName) != SyntaxKind.None)
131
return;
132
133
var instancePropertyName = "Instance" + propertyName;
134
if (HasMemberConflict(field, propertyName) || HasMemberConflict(field, instancePropertyName))
135
return;
136
137
var properties = ImmutableDictionary<string, string?>.Empty
138
.Add("PropertyName", propertyName)
139
.Add("InstancePropertyName", instancePropertyName);
140
context.ReportDiagnostic(Diagnostic.Create(FieldCanUsePartialProperty, variable.Identifier.GetLocation(), properties, field.Name, instancePropertyName));
141
}
142
143
private static bool HasMemberConflict(IFieldSymbol field, string memberName) => field.ContainingType
144
.GetMembers(memberName)
145
.Any(member => !SymbolEqualityComparer.Default.Equals(member, field));
146
147
private static bool SupportsNet10PartialProperties(SyntaxNodeAnalysisContext context)
148
{
149
if (context.Node.SyntaxTree.Options is not CSharpParseOptions parseOptions || parseOptions.LanguageVersion < LanguageVersion.CSharp14)
150
return false;
151
152
if (context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue("build_property.TargetFramework", out var targetFramework))
153
return IsNet10OrGreater(targetFramework);
154
155
var targetFrameworkAttribute = context.Compilation.Assembly.GetAttributes().FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == TargetFrameworkAttributeName);
156
return targetFrameworkAttribute is not null
157
&& targetFrameworkAttribute.ConstructorArguments.Length > 0
158
&& targetFrameworkAttribute.ConstructorArguments[0].Value is string frameworkName
159
&& IsNet10OrGreater(frameworkName);
160
}
161
162
private static bool IsNet10OrGreater(string targetFramework)
163
{
164
if (targetFramework.StartsWith("net", StringComparison.OrdinalIgnoreCase)
165
&& !targetFramework.StartsWith("netstandard", StringComparison.OrdinalIgnoreCase)
166
&& !targetFramework.StartsWith("netcoreapp", StringComparison.OrdinalIgnoreCase))
167
{
168
var versionText = targetFramework.Substring(3).Split('-')[0];
169
return versionText.Contains(".") && Version.TryParse(versionText, out var version) && version.Major >= 10;
170
}
171
172
const string corePrefix = ".NETCoreApp,Version=v";
173
const string netPrefix = ".NET,Version=v";
174
var prefix = targetFramework.StartsWith(corePrefix, StringComparison.OrdinalIgnoreCase)
175
? corePrefix
176
: targetFramework.StartsWith(netPrefix, StringComparison.OrdinalIgnoreCase) ? netPrefix : null;
177
return prefix is not null
178
&& Version.TryParse(targetFramework.Substring(prefix.Length), out var frameworkVersion)
179
&& frameworkVersion.Major >= 10;
180
}
181
182
private static string GetGeneratedPropertyName(IFieldSymbol field)
183
{
184
var attribute = field.GetAttributes().FirstOrDefault(static candidate => candidate.AttributeClass?.ToDisplayString() == ProfilePropertyAttributeName);
185
var explicitName = attribute?.ConstructorArguments.Length > 0 ? attribute.ConstructorArguments[0].Value as string : null;
186
if (string.IsNullOrWhiteSpace(explicitName) && attribute is not null)
187
{
188
foreach (var namedArgument in attribute.NamedArguments)
189
if (namedArgument.Key == "PropertyName" && namedArgument.Value.Value is string namedValue)
190
explicitName = namedValue;
191
}
192
if (!string.IsNullOrWhiteSpace(explicitName))
193
return explicitName!;
194
var fieldName = field.Name.StartsWith("_", StringComparison.Ordinal) ? field.Name.Substring(1) : field.Name;
195
return fieldName.Length == 0 ? fieldName : char.ToUpperInvariant(fieldName[0]) + fieldName.Substring(1);
196
}
197
198
private static bool DerivesFromXfeProfile(INamedTypeSymbol? type)
199
{
200
for (var current = type?.BaseType; current is not null; current = current.BaseType)
201
if (current.ToDisplayString() == ProfileBaseTypeName)
202
return true;
203
return false;
204
}
205
72
206
private static string? GetCode(AttributeData attribute) => attribute.ConstructorArguments.Length > 0 ? attribute.ConstructorArguments[0].Value as string : null;
73
207
74
208
private static Location GetAttributeLocation(AttributeData attribute, VariableDeclaratorSyntax fallback) => attribute.ApplicationSyntaxReference?.GetSyntax().GetLocation() ?? fallback.GetLocation();
209
210
private static Location GetAttributeLocation(AttributeData attribute, PropertyDeclarationSyntax fallback) => attribute.ApplicationSyntaxReference?.GetSyntax().GetLocation() ?? fallback.GetLocation();
75
211
}
@@ -30,7 +30,7 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
30
30
DiagnosticSeverity.Error, true);
31
31
32
32
private static readonly DiagnosticDescriptor GeneratedPropertyConflict = new(
33
"XFE1002", "生成属性名称冲突", "字段“{0}”生成的成员名称“{1}”与另一个成员冲突", "XFEExtension.NetCore.AutoConfig.Generator",
33
"XFE1002", "生成属性名称冲突", "成员“{0}”生成的成员名称“{1}”与另一个成员冲突", "XFEExtension.NetCore.AutoConfig.Generator",
34
34
DiagnosticSeverity.Error, true);
35
35
36
36
private static readonly DiagnosticDescriptor MultipleVariableFieldUnsupported = new(
@@ -57,6 +57,10 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
57
57
"XFE1008", "配置类型必须继承 XFEProfile", "成员“{0}”使用了 ProfileProperty,但其包含类型未继承 XFEProfile", "XFEExtension.NetCore.AutoConfig.Generator",
58
58
DiagnosticSeverity.Error, true);
59
59
60
private static readonly DiagnosticDescriptor UnsupportedPartialProperty = new(
61
"XFE1009", "不支持的部分配置属性", "属性“{0}”必须使用 C# 14 的 public partial InstanceXxx {{ get; set; }} 声明,并且不能是 static、required、virtual 或显式接口实现", "XFEExtension.NetCore.AutoConfig.Generator",
62
DiagnosticSeverity.Error, true);
63
60
64
public void Initialize(IncrementalGeneratorInitializationContext context)
61
65
{
62
66
var attributedMembers = context.SyntaxProvider.ForAttributeWithMetadataName(
@@ -69,29 +73,29 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
69
73
70
74
private static void EmitSources(SourceProductionContext context, ImmutableArray<ISymbol> attributedMembers)
71
75
{
72
var fields = new List<IFieldSymbol>();
76
var members = new List<ISymbol>();
73
77
foreach (var member in attributedMembers)
74
78
{
75
if (member is not IFieldSymbol field)
79
if (member is not IFieldSymbol && member is not IPropertySymbol)
76
80
{
77
81
context.ReportDiagnostic(Diagnostic.Create(UnsupportedField, GetLocation(member), member.Name));
78
82
continue;
79
83
}
80
if (!fields.Any(existing => SymbolEqualityComparer.Default.Equals(existing, field)))
81
fields.Add(field);
84
if (!members.Any(existing => SymbolEqualityComparer.Default.Equals(existing, member)))
85
members.Add(member);
82
86
}
83
87
84
88
var profileGroups = new List<ProfileGroup>();
85
foreach (var field in fields)
89
foreach (var member in members)
86
90
{
87
var containingType = field.ContainingType;
91
var containingType = member.ContainingType;
88
92
var group = profileGroups.FirstOrDefault(candidate => SymbolEqualityComparer.Default.Equals(candidate.Type, containingType));
89
93
if (group is null)
90
94
{
91
95
group = new ProfileGroup(containingType);
92
96
profileGroups.Add(group);
93
97
}
94
group.Fields.Add(field);
98
group.Members.Add(member);
95
99
}
96
100
97
101
foreach (var group in profileGroups.OrderBy(static group => group.Type.ToDisplayString(), StringComparer.Ordinal))
@@ -99,11 +103,11 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
99
103
if (!ValidateProfileType(context, group.Type))
100
104
continue;
101
105
102
var validFields = ValidateAndCreateFieldModels(context, group.Type, group.Fields);
103
if (validFields.Count == 0)
106
var validMembers = ValidateAndCreateMemberModels(context, group.Type, group.Members);
107
if (validMembers.Count == 0)
104
108
continue;
105
109
106
var source = GenerateProfileSource(group.Type, validFields);
110
var source = GenerateProfileSource(group.Type, validMembers);
107
111
context.AddSource(CreateHintName(group.Type), SourceText.From(source, Encoding.UTF8));
108
112
}
109
113
}
@@ -160,12 +164,21 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
160
164
return isValid;
161
165
}
162
166
163
private static List<FieldModel> ValidateAndCreateFieldModels(SourceProductionContext context, INamedTypeSymbol type, List<IFieldSymbol> fields)
167
private static List<ProfileMemberModel> ValidateAndCreateMemberModels(SourceProductionContext context, INamedTypeSymbol type, List<ISymbol> members)
164
168
{
165
var models = new List<FieldModel>();
169
var models = new List<ProfileMemberModel>();
166
170
var invalidDeclarationKeys = new HashSet<string>(StringComparer.Ordinal);
167
foreach (var field in fields.OrderBy(static field => GetLocation(field).SourceTree?.FilePath, StringComparer.Ordinal).ThenBy(static field => GetLocation(field).SourceSpan.Start))
171
foreach (var member in members.OrderBy(static member => GetLocation(member).SourceTree?.FilePath, StringComparer.Ordinal).ThenBy(static member => GetLocation(member).SourceSpan.Start))
168
172
{
173
if (member is IPropertySymbol property)
174
{
175
var propertyModel = ValidateAndCreatePartialPropertyModel(context, property);
176
if (propertyModel is not null)
177
models.Add(propertyModel);
178
continue;
179
}
180
181
var field = (IFieldSymbol)member;
169
182
var fieldDeclaration = field.DeclaringSyntaxReferences.Select(static reference => reference.GetSyntax()).OfType<VariableDeclaratorSyntax>().Select(static variable => variable.Parent?.Parent).OfType<FieldDeclarationSyntax>().FirstOrDefault();
170
183
if (fieldDeclaration is not null && fieldDeclaration.Declaration.Variables.Count != 1)
171
184
{
@@ -186,11 +199,11 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
186
199
context.ReportDiagnostic(Diagnostic.Create(GeneratedPropertyConflict, GetLocation(field), field.Name, propertyName));
187
200
continue;
188
201
}
189
models.Add(new FieldModel(field, propertyName, GetAttributeStrings(field, ProfilePropertyAddGetAttributeName), GetAttributeStrings(field, ProfilePropertyAddSetAttributeName)));
202
models.Add(new ProfileMemberModel(field, field.Type, propertyName, field.Name, false, GetAttributeStrings(field, ProfilePropertyAddGetAttributeName), GetAttributeStrings(field, ProfilePropertyAddSetAttributeName)));
190
203
}
191
204
192
var invalidModels = new HashSet<FieldModel>();
193
var generatedNames = new Dictionary<string, FieldModel>(StringComparer.Ordinal);
205
var invalidModels = new HashSet<ProfileMemberModel>();
206
var generatedNames = new Dictionary<string, ProfileMemberModel>(StringComparer.Ordinal);
194
207
foreach (var model in models)
195
208
{
196
209
var names = new[] { model.PropertyName, "Instance" + model.PropertyName, "Get" + model.PropertyName + "Property", "Set" + model.PropertyName + "Property" };
@@ -198,7 +211,7 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
198
211
{
199
212
if (generatedNames.TryGetValue(name, out var existingModel))
200
213
{
201
context.ReportDiagnostic(Diagnostic.Create(GeneratedPropertyConflict, GetLocation(model.Field), model.Field.Name, name));
214
context.ReportDiagnostic(Diagnostic.Create(GeneratedPropertyConflict, GetLocation(model.Member), model.Member.Name, name));
202
215
invalidModels.Add(model);
203
216
invalidModels.Add(existingModel);
204
217
}
@@ -209,10 +222,13 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
209
222
210
223
if ((name == "Get" + model.PropertyName + "Property" || name == "Set" + model.PropertyName + "Property") && IsPartialHook(type, name))
211
224
continue;
212
var conflictingMember = type.GetMembers(name).FirstOrDefault(member => !SymbolEqualityComparer.Default.Equals(member, model.Field));
225
var conflictingMember = type.GetMembers(name).FirstOrDefault(member =>
226
!(model.IsPartialProperty
227
&& name == model.StorageMemberName
228
&& SymbolEqualityComparer.Default.Equals(member, model.Member)));
213
229
if (conflictingMember is null)
214
230
continue;
215
context.ReportDiagnostic(Diagnostic.Create(GeneratedPropertyConflict, GetLocation(model.Field), model.Field.Name, name));
231
context.ReportDiagnostic(Diagnostic.Create(GeneratedPropertyConflict, GetLocation(model.Member), model.Member.Name, name));
216
232
invalidModels.Add(model);
217
233
}
218
234
}
@@ -220,7 +236,63 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
220
236
return models.Where(model => !invalidModels.Contains(model)).ToList();
221
237
}
222
238
223
private static string GenerateProfileSource(INamedTypeSymbol type, List<FieldModel> fields)
239
private static ProfileMemberModel? ValidateAndCreatePartialPropertyModel(SourceProductionContext context, IPropertySymbol property)
240
{
241
var declaration = property.DeclaringSyntaxReferences
242
.Select(static reference => reference.GetSyntax())
243
.OfType<PropertyDeclarationSyntax>()
244
.FirstOrDefault(static candidate => candidate.AttributeLists.Count > 0);
245
var parseOptions = declaration?.SyntaxTree.Options as CSharpParseOptions;
246
var accessors = declaration?.AccessorList?.Accessors;
247
var hasSupportedAccessors = accessors is { Count: 2 }
248
&& accessors.Value.Any(static accessor => accessor.IsKind(SyntaxKind.GetAccessorDeclaration) && accessor.Body is null && accessor.ExpressionBody is null && !accessor.SemicolonToken.IsMissing)
249
&& accessors.Value.Any(static accessor => accessor.IsKind(SyntaxKind.SetAccessorDeclaration) && accessor.Body is null && accessor.ExpressionBody is null && !accessor.SemicolonToken.IsMissing)
250
&& accessors.Value.All(static accessor => accessor.Modifiers.Count == 0);
251
var propertyName = GetGeneratedPropertyName(property);
252
if (!IsValidGeneratedIdentifier(propertyName))
253
{
254
context.ReportDiagnostic(Diagnostic.Create(GeneratedPropertyConflict, GetLocation(property), property.Name, propertyName));
255
return null;
256
}
257
var expectedInstanceName = "Instance" + propertyName;
258
var isSupported = declaration is not null
259
&& parseOptions is not null
260
&& parseOptions.LanguageVersion >= LanguageVersion.CSharp14
261
&& declaration.Modifiers.Any(SyntaxKind.PartialKeyword)
262
&& declaration.Modifiers.All(static modifier => modifier.IsKind(SyntaxKind.PublicKeyword) || modifier.IsKind(SyntaxKind.PartialKeyword))
263
&& property.DeclaredAccessibility == Accessibility.Public
264
&& !property.IsStatic
265
&& !property.IsAbstract
266
&& !property.IsVirtual
267
&& !property.IsOverride
268
&& !property.IsSealed
269
&& !property.IsRequired
270
&& property.ExplicitInterfaceImplementations.Length == 0
271
&& property.Parameters.Length == 0
272
&& property.RefKind == RefKind.None
273
&& property.GetMethod is not null
274
&& property.SetMethod is not null
275
&& !property.SetMethod.IsInitOnly
276
&& hasSupportedAccessors
277
&& property.Name == expectedInstanceName;
278
279
if (!isSupported)
280
{
281
context.ReportDiagnostic(Diagnostic.Create(UnsupportedPartialProperty, GetLocation(property), property.Name));
282
return null;
283
}
284
285
return new ProfileMemberModel(
286
property,
287
property.Type,
288
propertyName,
289
property.Name,
290
true,
291
GetAttributeStrings(property, ProfilePropertyAddGetAttributeName),
292
GetAttributeStrings(property, ProfilePropertyAddSetAttributeName));
293
}
294
295
private static string GenerateProfileSource(INamedTypeSymbol type, List<ProfileMemberModel> members)
224
296
{
225
297
var builder = new StringBuilder();
226
298
var typeName = EscapeIdentifier(type.Name);
@@ -284,34 +356,35 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
284
356
builder.AppendLine(" this.PropertyInfoDictionary.Clear();");
285
357
builder.AppendLine(" this.PropertySetFuncDictionary.Clear();");
286
358
builder.AppendLine(" this.PropertyGetFuncDictionary.Clear();");
287
foreach (var field in fields)
359
foreach (var member in members)
288
360
{
289
var fieldName = EscapeIdentifier(field.Field.Name);
290
var propertyName = EscapeIdentifier(field.PropertyName);
291
var declarationTypeDisplay = field.Field.Type.ToDisplayString(DeclarationTypeDisplayFormat);
292
var runtimeTypeDisplay = field.Field.Type.ToDisplayString(RuntimeTypeDisplayFormat);
361
var storageMemberName = EscapeIdentifier(member.StorageMemberName);
362
var propertyName = EscapeIdentifier(member.PropertyName);
363
var declarationTypeDisplay = member.Type.ToDisplayString(DeclarationTypeDisplayFormat);
364
var runtimeTypeDisplay = member.Type.ToDisplayString(RuntimeTypeDisplayFormat);
293
365
builder.Append(" this.PropertyInfoDictionary[nameof(").Append(propertyName).Append(")] = typeof(").Append(runtimeTypeDisplay).AppendLine(");");
294
builder.Append(" this.PropertySetFuncDictionary[nameof(").Append(propertyName).Append(")] = value => this.").Append(fieldName).Append(" = (").Append(declarationTypeDisplay).AppendLine(")value!;");
295
builder.Append(" this.PropertyGetFuncDictionary[nameof(").Append(propertyName).Append(")] = () => this.").Append(fieldName).AppendLine(";");
366
builder.Append(" this.PropertySetFuncDictionary[nameof(").Append(propertyName).Append(")] = value => this.").Append(storageMemberName).Append(" = (").Append(declarationTypeDisplay).AppendLine(")value!;");
367
builder.Append(" this.PropertyGetFuncDictionary[nameof(").Append(propertyName).Append(")] = () => this.").Append(storageMemberName).AppendLine(";");
296
368
}
297
369
builder.AppendLine(" this.__BindProfileOwnedCollections();");
298
370
builder.AppendLine(" }");
299
371
builder.AppendLine();
300
372
builder.AppendLine(" private void __BindProfileOwnedCollections()");
301
373
builder.AppendLine(" {");
302
foreach (var field in fields)
374
foreach (var member in members)
303
375
{
304
if (!IsProfileOwnedCollection(field.Field.Type))
376
if (!IsProfileOwnedCollection(member.Type))
305
377
continue;
306
var fieldName = EscapeIdentifier(field.Field.Name);
307
builder.Append(" if ((object?)this.").Append(fieldName).Append(" is global::XFEExtension.NetCore.AutoConfig.IProfileOwnedCollection owned_").Append(field.Field.Name).AppendLine(")");
308
builder.Append(" owned_").Append(field.Field.Name).AppendLine(".CurrentProfile = this;");
378
var storageMemberName = EscapeIdentifier(member.StorageMemberName);
379
var safeLocalSuffix = new string(member.PropertyName.Select(static character => char.IsLetterOrDigit(character) ? character : '_').ToArray());
380
builder.Append(" if ((object?)this.").Append(storageMemberName).Append(" is global::XFEExtension.NetCore.AutoConfig.IProfileOwnedCollection owned_").Append(safeLocalSuffix).AppendLine(")");
381
builder.Append(" owned_").Append(safeLocalSuffix).AppendLine(".CurrentProfile = this;");
309
382
}
310
383
builder.AppendLine(" }");
311
384
builder.AppendLine();
312
385
AppendProfileOperations(builder, typeName);
313
foreach (var field in fields)
314
AppendFieldMembers(builder, field);
386
foreach (var member in members)
387
AppendProfileMember(builder, member);
315
388
builder.AppendLine("}");
316
389
return builder.ToString();
317
390
}
@@ -391,15 +464,15 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
391
464
builder.AppendLine();
392
465
}
393
466
394
private static void AppendFieldMembers(StringBuilder builder, FieldModel field)
467
private static void AppendProfileMember(StringBuilder builder, ProfileMemberModel member)
395
468
{
396
var fieldName = EscapeIdentifier(field.Field.Name);
397
var propertyName = EscapeIdentifier(field.PropertyName);
469
var storageMemberName = EscapeIdentifier(member.StorageMemberName);
470
var propertyName = EscapeIdentifier(member.PropertyName);
398
471
var instancePropertyName = "Instance" + propertyName;
399
472
var getMethodName = "Get" + propertyName + "Property";
400
473
var setMethodName = "Set" + propertyName + "Property";
401
var typeDisplay = field.Field.Type.ToDisplayString(DeclarationTypeDisplayFormat);
402
var xmlElementNameLiteral = SyntaxFactory.Literal(field.PropertyName).ToFullString();
474
var typeDisplay = member.Type.ToDisplayString(DeclarationTypeDisplayFormat);
475
var xmlElementNameLiteral = SyntaxFactory.Literal(member.PropertyName).ToFullString();
403
476
404
477
builder.Append(" static partial void ").Append(getMethodName).AppendLine("();");
405
478
builder.Append(" static partial void ").Append(setMethodName).Append("(ref ").Append(typeDisplay).AppendLine(" value);");
@@ -413,10 +486,10 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
413
486
builder.AppendLine(" lock (__current.ProfileSyncRoot)");
414
487
builder.AppendLine(" {");
415
488
builder.Append(" ").Append(getMethodName).AppendLine("();");
416
if (field.GetStatements.Length == 0)
417
builder.Append(" return __current.").Append(fieldName).AppendLine(";");
489
if (member.GetStatements.Length == 0)
490
builder.Append(" return __current.").Append(storageMemberName).AppendLine(";");
418
491
else
419
AppendStatements(builder, field.GetStatements, 16);
492
AppendStatements(builder, member.GetStatements, 16);
420
493
builder.AppendLine(" }");
421
494
builder.AppendLine(" }");
422
495
builder.AppendLine(" set");
@@ -425,11 +498,11 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
425
498
builder.AppendLine(" lock (__current.ProfileSyncRoot)");
426
499
builder.AppendLine(" {");
427
500
builder.Append(" ").Append(setMethodName).AppendLine("(ref value);");
428
if (field.SetStatements.Length == 0)
429
builder.Append(" __current.").Append(fieldName).AppendLine(" = value;");
501
if (member.SetStatements.Length == 0)
502
builder.Append(" __current.").Append(storageMemberName).AppendLine(" = value;");
430
503
else
431
AppendStatements(builder, field.SetStatements, 16);
432
if (IsProfileOwnedCollection(field.Field.Type))
504
AppendStatements(builder, member.SetStatements, 16);
505
if (IsProfileOwnedCollection(member.Type) && !member.IsPartialProperty)
433
506
builder.AppendLine(" __current.__BindProfileOwnedCollections();");
434
507
builder.AppendLine(" __current.InstanceRequestSaveProfile();");
435
508
builder.AppendLine(" }");
@@ -438,13 +511,23 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
438
511
builder.AppendLine();
439
512
builder.AppendLine(" [global::XFEExtension.NetCore.AutoConfig.ProfileFieldAutoGenerateAttribute]");
440
513
builder.Append(" [global::System.Xml.Serialization.XmlElementAttribute(").Append(xmlElementNameLiteral).AppendLine(")]");
441
builder.Append(" public ").Append(typeDisplay).Append(' ').Append(instancePropertyName).AppendLine();
514
builder.Append(" public ");
515
if (member.IsPartialProperty)
516
builder.Append("partial ");
517
builder.Append(typeDisplay).Append(' ').Append(instancePropertyName).AppendLine();
442
518
builder.AppendLine(" {");
443
builder.Append(" get { lock (ProfileSyncRoot) return this.").Append(fieldName).AppendLine("; }");
444
if (IsProfileOwnedCollection(field.Field.Type))
445
builder.Append(" set { lock (ProfileSyncRoot) { this.").Append(fieldName).AppendLine(" = value; this.__BindProfileOwnedCollections(); } }");
519
builder.Append(" get { lock (ProfileSyncRoot) return ");
520
builder.Append(member.IsPartialProperty ? "field" : "this." + storageMemberName).AppendLine("; }");
521
if (IsProfileOwnedCollection(member.Type))
522
{
523
builder.Append(" set { lock (ProfileSyncRoot) { ");
524
builder.Append(member.IsPartialProperty ? "field" : "this." + storageMemberName).AppendLine(" = value; this.__BindProfileOwnedCollections(); } }");
525
}
446
526
else
447
builder.Append(" set { lock (ProfileSyncRoot) this.").Append(fieldName).AppendLine(" = value; }");
527
{
528
builder.Append(" set { lock (ProfileSyncRoot) ");
529
builder.Append(member.IsPartialProperty ? "field" : "this." + storageMemberName).AppendLine(" = value; }");
530
}
448
531
builder.AppendLine(" }");
449
532
builder.AppendLine();
450
533
}
@@ -462,9 +545,9 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
462
545
}
463
546
}
464
547
465
private static string GetGeneratedPropertyName(IFieldSymbol field)
548
private static string GetGeneratedPropertyName(ISymbol member)
466
549
{
467
var attribute = GetAttribute(field, ProfilePropertyAttributeName);
550
var attribute = GetAttribute(member, ProfilePropertyAttributeName);
468
551
var explicitName = GetStringArgument(attribute);
469
552
if (string.IsNullOrWhiteSpace(explicitName) && attribute is not null)
470
553
{
@@ -475,7 +558,10 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
475
558
if (!string.IsNullOrWhiteSpace(explicitName))
476
559
return explicitName!;
477
560
478
var fieldName = field.Name.StartsWith("_", StringComparison.Ordinal) ? field.Name.Substring(1) : field.Name;
561
if (member is IPropertySymbol property)
562
return property.Name.StartsWith("Instance", StringComparison.Ordinal) ? property.Name.Substring("Instance".Length) : property.Name;
563
564
var fieldName = member.Name.StartsWith("_", StringComparison.Ordinal) ? member.Name.Substring(1) : member.Name;
479
565
if (fieldName.Length == 0)
480
566
return fieldName;
481
567
return char.ToUpperInvariant(fieldName[0]) + fieldName.Substring(1);
@@ -491,10 +577,10 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
491
577
492
578
private static string? GetProfilePath(INamedTypeSymbol type) => GetStringArgument(GetAttribute(type, ProfilePathAttributeName));
493
579
494
private static ImmutableArray<string> GetAttributeStrings(IFieldSymbol field, string metadataName)
580
private static ImmutableArray<string> GetAttributeStrings(ISymbol member, string metadataName)
495
581
{
496
582
var builder = ImmutableArray.CreateBuilder<string>();
497
foreach (var attribute in field.GetAttributes().Where(attribute => IsAttribute(attribute, metadataName)))
583
foreach (var attribute in member.GetAttributes().Where(attribute => IsAttribute(attribute, metadataName)))
498
584
{
499
585
var value = GetStringArgument(attribute);
500
586
if (!string.IsNullOrWhiteSpace(value))
@@ -545,21 +631,27 @@ public sealed class ProfilePropertyAutoGenerator : IIncrementalGenerator
545
631
{
546
632
public ProfileGroup(INamedTypeSymbol type) => Type = type;
547
633
public INamedTypeSymbol Type { get; }
548
public List<IFieldSymbol> Fields { get; } = new();
634
public List<ISymbol> Members { get; } = new();
549
635
}
550
636
551
private sealed class FieldModel
637
private sealed class ProfileMemberModel
552
638
{
553
public FieldModel(IFieldSymbol field, string propertyName, ImmutableArray<string> getStatements, ImmutableArray<string> setStatements)
639
public ProfileMemberModel(ISymbol member, ITypeSymbol type, string propertyName, string storageMemberName, bool isPartialProperty, ImmutableArray<string> getStatements, ImmutableArray<string> setStatements)
554
640
{
555
Field = field;
641
Member = member;
642
Type = type;
556
643
PropertyName = propertyName;
644
StorageMemberName = storageMemberName;
645
IsPartialProperty = isPartialProperty;
557
646
GetStatements = getStatements;
558
647
SetStatements = setStatements;
559
648
}
560
649
561
public IFieldSymbol Field { get; }
650
public ISymbol Member { get; }
651
public ITypeSymbol Type { get; }
562
652
public string PropertyName { get; }
653
public string StorageMemberName { get; }
654
public bool IsPartialProperty { get; }
563
655
public ImmutableArray<string> GetStatements { get; }
564
656
public ImmutableArray<string> SetStatements { get; }
565
657
}
@@ -3,10 +3,15 @@ using Microsoft.CodeAnalysis.CodeActions;
3
3
using Microsoft.CodeAnalysis.CodeFixes;
4
4
using Microsoft.CodeAnalysis.CSharp;
5
5
using Microsoft.CodeAnalysis.CSharp.Syntax;
6
using Microsoft.CodeAnalysis.FindSymbols;
7
using Microsoft.CodeAnalysis.Formatting;
6
8
using Microsoft.CodeAnalysis.Text;
9
using System;
10
using System.Collections.Generic;
7
11
using System.Collections.Immutable;
8
12
using System.Composition;
9
13
using System.Linq;
14
using System.Text.RegularExpressions;
10
15
using System.Threading;
11
16
using System.Threading.Tasks;
12
17
using XFEExtension.NetCore.AutoConfig.Diagnostics;
@@ -16,7 +21,11 @@ namespace XFEExtension.NetCore.AutoConfig.CodeFix;
16
21
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AutoConfigCodeFixProvider)), Shared]
17
22
public sealed class AutoConfigCodeFixProvider : CodeFixProvider
18
23
{
19
public override ImmutableArray<string> FixableDiagnosticIds => [AutoConfigDiagnostics.AddGetNoResultErrorId, AutoConfigDiagnostics.AddSetNoSetResultWarningId];
24
private const string ProfilePropertyAttributeName = "XFEExtension.NetCore.AutoConfig.ProfilePropertyAttribute";
25
private const string AddGetAttributeName = "XFEExtension.NetCore.AutoConfig.ProfilePropertyAddGetAttribute";
26
private const string AddSetAttributeName = "XFEExtension.NetCore.AutoConfig.ProfilePropertyAddSetAttribute";
27
28
public override ImmutableArray<string> FixableDiagnosticIds => [AutoConfigDiagnostics.AddGetNoResultErrorId, AutoConfigDiagnostics.AddSetNoSetResultWarningId, AutoConfigDiagnostics.FieldCanUsePartialPropertyId];
20
29
21
30
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
22
31
@@ -36,6 +45,17 @@ public sealed class AutoConfigCodeFixProvider : CodeFixProvider
36
45
CodeAction.Create("添加字段的设置方法", cancellationToken => AddAttributeAsync(context.Document, diagnostic.Location.SourceSpan, "ProfilePropertyAddSet", "Current.{0} = value", cancellationToken), "添加字段的设置方法"),
37
46
diagnostic);
38
47
}
48
else if (diagnostic.Id == AutoConfigDiagnostics.FieldCanUsePartialPropertyId
49
&& diagnostic.Properties.TryGetValue("InstancePropertyName", out var instancePropertyName)
50
&& !string.IsNullOrWhiteSpace(instancePropertyName))
51
{
52
context.RegisterCodeFix(
53
CodeAction.Create(
54
"转换为 .NET 10 部分配置属性",
55
cancellationToken => ConvertToPartialPropertyAsync(context.Document, diagnostic.Location.SourceSpan, instancePropertyName!, cancellationToken),
56
"转换为部分配置属性"),
57
diagnostic);
58
}
39
59
}
40
60
return Task.CompletedTask;
41
61
}
@@ -55,4 +75,165 @@ public sealed class AutoConfigCodeFixProvider : CodeFixProvider
55
75
var newRoot = root.ReplaceNode(fieldDeclaration, fieldDeclaration.AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(newAttribute))));
56
76
return document.WithSyntaxRoot(newRoot);
57
77
}
78
79
private static async Task<Solution> ConvertToPartialPropertyAsync(Document document, TextSpan sourceSpan, string instancePropertyName, CancellationToken cancellationToken)
80
{
81
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
82
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
83
if (root is null || semanticModel is null)
84
return document.Project.Solution;
85
var variable = root.FindToken(sourceSpan.Start).Parent?.AncestorsAndSelf().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
86
var fieldDeclaration = variable?.Parent?.Parent as FieldDeclarationSyntax;
87
if (variable is null
88
|| fieldDeclaration is null
89
|| fieldDeclaration.Declaration.Variables.Count != 1
90
|| semanticModel.GetDeclaredSymbol(variable, cancellationToken) is not IFieldSymbol field)
91
return document.Project.Solution;
92
93
var originalFieldName = field.Name;
94
var profileAttributeNames = new HashSet<string>(StringComparer.Ordinal);
95
var getHookAttributeNames = new HashSet<string>(StringComparer.Ordinal);
96
var setHookAttributeNames = new HashSet<string>(StringComparer.Ordinal);
97
foreach (var attribute in fieldDeclaration.AttributeLists.SelectMany(static list => list.Attributes))
98
{
99
var attributeTypeName = (semanticModel.GetSymbolInfo(attribute, cancellationToken).Symbol as IMethodSymbol)?.ContainingType.ToDisplayString();
100
if (attributeTypeName != ProfilePropertyAttributeName && attributeTypeName != AddGetAttributeName && attributeTypeName != AddSetAttributeName)
101
continue;
102
var sourceName = attribute.Name.ToString();
103
profileAttributeNames.Add(sourceName);
104
if (attributeTypeName == AddGetAttributeName)
105
getHookAttributeNames.Add(sourceName);
106
else if (attributeTypeName == AddSetAttributeName)
107
setHookAttributeNames.Add(sourceName);
108
}
109
var solution = document.Project.Solution;
110
var referencedSymbols = await SymbolFinder.FindReferencesAsync(field, solution, cancellationToken).ConfigureAwait(false);
111
var referenceLocations = referencedSymbols
112
.SelectMany(static referencedSymbol => referencedSymbol.Locations)
113
.Where(static location => location.Location.IsInSource)
114
.GroupBy(static location => location.Document.Id);
115
var declarationAnnotation = new SyntaxAnnotation();
116
solution = solution.WithDocumentSyntaxRoot(
117
document.Id,
118
root.ReplaceNode(fieldDeclaration, fieldDeclaration.WithAdditionalAnnotations(declarationAnnotation)));
119
120
foreach (var documentLocations in referenceLocations)
121
{
122
var referenceDocument = solution.GetDocument(documentLocations.Key);
123
var referenceRoot = referenceDocument is null ? null : await referenceDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
124
if (referenceDocument is null || referenceRoot is null)
125
continue;
126
var tokens = documentLocations
127
.Select(location => referenceRoot.FindToken(location.Location.SourceSpan.Start))
128
.Where(token => token.IsKind(SyntaxKind.IdentifierToken) && token.ValueText == originalFieldName)
129
.Distinct()
130
.ToArray();
131
if (tokens.Length == 0)
132
continue;
133
var renamedRoot = referenceRoot.ReplaceTokens(tokens, (_, rewritten) => SyntaxFactory.Identifier(rewritten.LeadingTrivia, instancePropertyName, rewritten.TrailingTrivia));
134
solution = solution.WithDocumentSyntaxRoot(referenceDocument.Id, renamedRoot);
135
}
136
137
var declarationDocument = solution.GetDocument(document.Id);
138
var declarationRoot = declarationDocument is null ? null : await declarationDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
139
if (declarationDocument is null || declarationRoot is null)
140
return solution;
141
var currentFieldDeclaration = declarationRoot.GetAnnotatedNodes(declarationAnnotation)
142
.OfType<FieldDeclarationSyntax>()
143
.Where(static candidate => candidate.Declaration.Variables.Count == 1)
144
.FirstOrDefault(candidate => candidate.Declaration.Variables[0].Identifier.ValueText == originalFieldName);
145
if (currentFieldDeclaration is null)
146
return solution;
147
var currentVariable = currentFieldDeclaration.Declaration.Variables[0];
148
var attributeLists = PreparePartialPropertyAttributes(
149
currentFieldDeclaration.AttributeLists,
150
originalFieldName,
151
instancePropertyName,
152
profileAttributeNames,
153
getHookAttributeNames,
154
setHookAttributeNames);
155
var partialProperty = SyntaxFactory.PropertyDeclaration(currentFieldDeclaration.Declaration.Type.WithoutTrivia(), SyntaxFactory.Identifier(instancePropertyName))
156
.WithAttributeLists(attributeLists)
157
.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.PartialKeyword)))
158
.WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List([
159
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
160
SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
161
])))
162
.WithInitializer(currentVariable.Initializer)
163
.WithSemicolonToken(currentVariable.Initializer is null ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken))
164
.WithLeadingTrivia(currentFieldDeclaration.GetLeadingTrivia())
165
.WithTrailingTrivia(currentFieldDeclaration.GetTrailingTrivia())
166
.WithAdditionalAnnotations(Formatter.Annotation);
167
var updatedRoot = declarationRoot.ReplaceNode(currentFieldDeclaration, partialProperty);
168
return solution.WithDocumentSyntaxRoot(declarationDocument.Id, updatedRoot);
169
}
170
171
private static SyntaxList<AttributeListSyntax> RewriteHookAttributeStrings(
172
SyntaxList<AttributeListSyntax> attributeLists,
173
string fieldName,
174
string instancePropertyName,
175
HashSet<string> getHookAttributeNames,
176
HashSet<string> setHookAttributeNames)
177
{
178
return SyntaxFactory.List(attributeLists.Select(attributeList => attributeList.ReplaceNodes(
179
attributeList.Attributes,
180
(_, attribute) =>
181
{
182
var attributeName = attribute.Name.ToString();
183
var isGetHook = getHookAttributeNames.Contains(attributeName);
184
if (!isGetHook && !setHookAttributeNames.Contains(attributeName))
185
return attribute;
186
var arguments = attribute.ArgumentList?.Arguments;
187
if (arguments is not { Count: > 0 }
188
|| arguments.Value[0].Expression is not LiteralExpressionSyntax literal
189
|| !literal.IsKind(SyntaxKind.StringLiteralExpression))
190
return attribute;
191
var rewrittenCode = literal.Token.ValueText;
192
if (isGetHook || fieldName != "value")
193
{
194
rewrittenCode = Regex.Replace(rewrittenCode, $@"\b{Regex.Escape(fieldName)}\b", instancePropertyName);
195
}
196
else
197
{
198
rewrittenCode = Regex.Replace(
199
rewrittenCode,
200
$@"(?<memberAccess>\.\s*){Regex.Escape(fieldName)}\b",
201
"${memberAccess}" + instancePropertyName);
202
}
203
var rewrittenLiteral = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(rewrittenCode));
204
return attribute.ReplaceNode(literal, rewrittenLiteral);
205
})));
206
}
207
208
private static SyntaxList<AttributeListSyntax> PreparePartialPropertyAttributes(
209
SyntaxList<AttributeListSyntax> attributeLists,
210
string fieldName,
211
string instancePropertyName,
212
HashSet<string> profileAttributeNames,
213
HashSet<string> getHookAttributeNames,
214
HashSet<string> setHookAttributeNames)
215
{
216
var rewrittenLists = RewriteHookAttributeStrings(attributeLists, fieldName, instancePropertyName, getHookAttributeNames, setHookAttributeNames);
217
var result = new List<AttributeListSyntax>();
218
foreach (var attributeList in rewrittenLists)
219
{
220
var propertyAttributes = attributeList.Attributes.Where(attribute => profileAttributeNames.Contains(attribute.Name.ToString())).ToArray();
221
var backingFieldAttributes = attributeList.Attributes.Where(attribute => !profileAttributeNames.Contains(attribute.Name.ToString())).ToArray();
222
if (propertyAttributes.Length > 0)
223
{
224
result.Add(attributeList
225
.WithTarget(null)
226
.WithAttributes(SyntaxFactory.SeparatedList(propertyAttributes)));
227
}
228
if (backingFieldAttributes.Length > 0)
229
{
230
result.Add(attributeList
231
.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.FieldKeyword))
232
.WithColonToken(SyntaxFactory.Token(SyntaxKind.ColonToken)))
233
.WithAttributes(SyntaxFactory.SeparatedList(backingFieldAttributes))
234
.WithLeadingTrivia(propertyAttributes.Length == 0 ? attributeList.GetLeadingTrivia() : default));
235
}
236
}
237
return SyntaxFactory.List(result);
238
}
58
239
}
@@ -71,6 +71,28 @@ public sealed class GeneratorAndCodeFixTests
71
71
Assert.Equal("7B0B7B07FE1271B592876778731820ACB41520A9F836C6D3F7501735F9A839A8", hash);
72
72
}
73
73
74
[Fact]
75
public void GeneratorImplementsNet10PartialProfileProperty()
76
{
77
const string source = """
78
using XFEExtension.NetCore.AutoConfig;
79
[AutoLoadProfile(false)]
80
public partial class Settings : XFEProfile
81
{
82
[ProfileProperty]
83
public partial string InstanceName { get; set; } = "default";
84
}
85
""";
86
87
var (result, outputCompilation) = RunGenerator(source);
88
var generatedSource = result.Results.Single().GeneratedSources.Single().SourceText.ToString();
89
90
Assert.Contains("public static string Name", generatedSource);
91
Assert.Contains("public partial string InstanceName", generatedSource);
92
Assert.Contains("get { lock (ProfileSyncRoot) return field; }", generatedSource);
93
Assert.DoesNotContain(outputCompilation.GetDiagnostics(), diagnostic => diagnostic.Severity == DiagnosticSeverity.Error);
94
}
95
74
96
[Theory]
75
97
[InlineData("public class Settings : XFEProfile { [ProfileProperty] private int value; }", "XFE1001")]
76
98
[InlineData("public partial class Settings : XFEProfile { [ProfileProperty] private int first, second; }", "XFE1003")]
@@ -78,6 +100,7 @@ public sealed class GeneratorAndCodeFixTests
78
100
[InlineData("public partial class Settings : XFEProfile { public Settings(int value) { } [ProfileProperty] private int value; }", "XFE1005")]
79
101
[InlineData("public partial class Settings : XFEProfile { public static Settings Current { get; set; } = null!; [ProfileProperty] private int value; }", "XFE1006")]
80
102
[InlineData("public partial class Settings { [ProfileProperty] private int value; }", "XFE1008")]
103
[InlineData("public partial class Settings : XFEProfile { [ProfileProperty] public partial int Value { get; set; } }", "XFE1009")]
81
104
public void GeneratorReportsActionableUsageDiagnostics(string declaration, string diagnosticId)
82
105
{
83
106
var source = "using XFEExtension.NetCore.AutoConfig;\n" + declaration;
@@ -125,6 +148,104 @@ public sealed class GeneratorAndCodeFixTests
125
148
Assert.Single(diagnostics, diagnostic => diagnostic.Id == AutoConfigDiagnostics.AddSetNoSetResultWarningId);
126
149
}
127
150
151
[Theory]
152
[InlineData(".NETCoreApp,Version=v10.0", true)]
153
[InlineData(".NETCoreApp,Version=v11.0", true)]
154
[InlineData(".NETCoreApp,Version=v9.0", false)]
155
public async Task FieldUpgradeSuggestionRequiresNet10OrGreater(string targetFramework, bool expected)
156
{
157
var source = $$"""
158
using XFEExtension.NetCore.AutoConfig;
159
[assembly: global::System.Runtime.Versioning.TargetFramework("{{targetFramework}}")]
160
public partial class Settings : XFEProfile
161
{
162
[ProfileProperty]
163
private string value = "default";
164
}
165
""";
166
var compilation = CreateCompilation(source);
167
168
var diagnostics = await compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(new AutoConfigDiagnostics())).GetAnalyzerDiagnosticsAsync();
169
170
Assert.Equal(expected, diagnostics.Any(diagnostic => diagnostic.Id == AutoConfigDiagnostics.FieldCanUsePartialPropertyId));
171
}
172
173
[Fact]
174
public async Task FieldUpgradeSuggestionRequiresCSharp14()
175
{
176
const string source = """
177
using XFEExtension.NetCore.AutoConfig;
178
[assembly: global::System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v10.0")]
179
public partial class Settings : XFEProfile
180
{
181
[ProfileProperty]
182
private string value = "default";
183
}
184
""";
185
var compilation = CreateCompilation(source, LanguageVersion.CSharp13);
186
187
var diagnostics = await compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(new AutoConfigDiagnostics())).GetAnalyzerDiagnosticsAsync();
188
189
Assert.DoesNotContain(diagnostics, diagnostic => diagnostic.Id == AutoConfigDiagnostics.FieldCanUsePartialPropertyId);
190
}
191
192
[Fact]
193
public async Task CodeFixUpgradesFieldToPartialPropertyAndRenamesReferences()
194
{
195
const string source = """
196
using XFEExtension.NetCore.AutoConfig;
197
using Profile = XFEExtension.NetCore.AutoConfig.ProfilePropertyAttribute;
198
using SetHook = XFEExtension.NetCore.AutoConfig.ProfilePropertyAddSetAttribute;
199
[assembly: global::System.Runtime.Versioning.TargetFramework(".NETCoreApp,Version=v10.0")]
200
public partial class Settings : XFEProfile
201
{
202
[Profile]
203
[SetHook("Current.value = value")]
204
[System.NonSerialized]
205
private string value = "default";
206
207
public string ReadValue() => value;
208
}
209
""";
210
using var workspace = new AdhocWorkspace();
211
var projectId = ProjectId.CreateNewId();
212
var documentId = DocumentId.CreateNewId(projectId);
213
var solution = workspace.CurrentSolution
214
.AddProject(projectId, "PartialPropertyCodeFixTest", "PartialPropertyCodeFixTest", LanguageNames.CSharp)
215
.WithProjectParseOptions(projectId, new CSharpParseOptions(LanguageVersion.Preview))
216
.WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable))
217
.AddMetadataReferences(projectId, GetMetadataReferences())
218
.AddDocument(documentId, "Settings.cs", SourceText.From(source));
219
Assert.True(workspace.TryApplyChanges(solution));
220
var document = workspace.CurrentSolution.GetDocument(documentId)!;
221
var compilation = (CSharpCompilation)(await document.Project.GetCompilationAsync())!;
222
var diagnostic = (await compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(new AutoConfigDiagnostics())).GetAnalyzerDiagnosticsAsync())
223
.Single(item => item.Id == AutoConfigDiagnostics.FieldCanUsePartialPropertyId);
224
var actions = new List<CodeAction>();
225
var context = new CodeFixContext(document, diagnostic, (action, _) => actions.Add(action), CancellationToken.None);
226
var provider = new AutoConfigCodeFixProvider();
227
228
await provider.RegisterCodeFixesAsync(context);
229
var operations = await actions.Single().GetOperationsAsync(CancellationToken.None);
230
var changedSolution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution;
231
var changedDocument = changedSolution.GetDocument(documentId)!;
232
var changedText = (await changedDocument.GetTextAsync()).ToString();
233
234
Assert.Contains("public partial string InstanceValue", changedText);
235
Assert.Contains("field:", changedText);
236
Assert.Contains("System.NonSerialized", changedText);
237
Assert.Contains("[Profile]", changedText);
238
Assert.Contains("Current.InstanceValue = value", changedText);
239
Assert.Contains("= \"default\";", changedText);
240
Assert.Contains("ReadValue() => InstanceValue", changedText);
241
var changedCompilation = (CSharpCompilation)(await changedDocument.Project.GetCompilationAsync())!;
242
GeneratorDriver driver = CSharpGeneratorDriver.Create(
243
generators: [new ProfilePropertyAutoGenerator().AsSourceGenerator()],
244
parseOptions: new CSharpParseOptions(LanguageVersion.Preview));
245
driver.RunGeneratorsAndUpdateCompilation(changedCompilation, out var outputCompilation, out _);
246
Assert.DoesNotContain(outputCompilation.GetDiagnostics(), item => item.Severity == DiagnosticSeverity.Error);
247
}
248
128
249
[Theory]
129
250
[InlineData("ProfilePropertyAddGet", "System.Console.WriteLine(1)", AutoConfigDiagnostics.AddGetNoResultErrorId, "return Current.value")]
130
251
[InlineData("ProfilePropertyAddSet", "System.Console.WriteLine(value)", AutoConfigDiagnostics.AddSetNoSetResultWarningId, "Current.value = value")]
@@ -174,9 +295,9 @@ public sealed class GeneratorAndCodeFixTests
174
295
return (driver.GetRunResult(), outputCompilation);
175
296
}
176
297
177
private static CSharpCompilation CreateCompilation(string source) => CSharpCompilation.Create(
298
private static CSharpCompilation CreateCompilation(string source, LanguageVersion languageVersion = LanguageVersion.Preview) => CSharpCompilation.Create(
178
299
"GeneratorTest_" + Guid.NewGuid().ToString("N"),
179
[CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.Preview))],
300
[CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(languageVersion))],
180
301
GetMetadataReferences(),
181
302
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable));
182
303
@@ -7,6 +7,15 @@ public partial class XfeRoundTripProfile : XFEProfile
7
7
private string value = "default";
8
8
}
9
9
10
[AutoLoadProfile(false)]
11
public partial class PartialPropertyProfile : XFEProfile
12
{
13
[ProfileProperty]
14
public partial string InstanceValue { get; set; } = "partial-default";
15
16
public PartialPropertyProfile() => DefaultProfileOperationMode = ProfileOperationMode.Xml;
17
}
18
10
19
[AutoLoadProfile(false)]
11
20
public partial class JsonRoundTripProfile : XFEProfile
12
21
{
@@ -31,6 +31,13 @@ public sealed class PersistenceTests
31
31
() => XmlRoundTripProfile.SaveProfileAsync(),
32
32
XmlRoundTripProfile.LoadProfile,
33
33
path => XmlRoundTripProfile.ProfilePath = path);
34
await AssertRoundTripAsync(
35
Path.Combine(directory, nameof(PartialPropertyProfile)),
36
value => PartialPropertyProfile.Value = value,
37
() => PartialPropertyProfile.Value,
38
() => PartialPropertyProfile.SaveProfileAsync(),
39
PartialPropertyProfile.LoadProfile,
40
path => PartialPropertyProfile.ProfilePath = path);
34
41
}
35
42
finally
36
43
{
@@ -44,9 +51,13 @@ public sealed class PersistenceTests
44
51
XmlRoundTripProfile.Current.InstanceValue = "canonical";
45
52
46
53
var xml = XmlRoundTripProfile.ExportProfile();
54
PartialPropertyProfile.Current.InstanceValue = "partial-canonical";
55
var partialXml = PartialPropertyProfile.ExportProfile();
47
56
48
57
Assert.Contains("<Value>canonical</Value>", xml);
49
58
Assert.DoesNotContain("<InstanceValue>", xml);
59
Assert.Contains("<Value>partial-canonical</Value>", partialXml);
60
Assert.DoesNotContain("<InstanceValue>", partialXml);
50
61
}
51
62
52
63
[Fact]
@@ -4,7 +4,7 @@
4
4
/// 向属性的Get方法中添加代码
5
5
/// </summary>
6
6
/// <param name="funcString">需要添加的代码</param>
7
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
7
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
8
8
public class ProfilePropertyAddGetAttribute(string funcString) : Attribute
9
9
{
10
10
/// <summary>
@@ -4,7 +4,7 @@
4
4
/// 向属性的Set方法中添加代码
5
5
/// </summary>
6
6
/// <param name="funcString">需要添加的代码</param>
7
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
7
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
8
8
public class ProfilePropertyAddSetAttribute(string funcString) : Attribute
9
9
{
10
10
/// <summary>
@@ -24,6 +24,7 @@
24
24
- 每实例 JSON 序列化选项、命名策略和 converter
25
25
- ProfileStore<TProfile> 多实例/多租户存储
26
26
- ProfileList/ProfileDictionary 所属配置自动绑定
27
- .NET 10 / C# 14 部分配置属性及字段升级诊断与代码修复
27
28
28
29
## 调整
29
30