From 28cb8e443e0a281b1b9c106c40cc53b3b6f00972 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Sat, 29 Jun 2024 00:17:03 +0200 Subject: [PATCH] fixed combined names being able to be outdated if additional enum values are added later --- DynamicEnums/DynamicEnum.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/DynamicEnums/DynamicEnum.cs b/DynamicEnums/DynamicEnum.cs index 82acad7..9050077 100644 --- a/DynamicEnums/DynamicEnum.cs +++ b/DynamicEnums/DynamicEnum.cs @@ -94,15 +94,18 @@ namespace DynamicEnums { /// Returns a string that represents the current object. /// A string that represents the current object. public override string ToString() { - if (this.name == null) { + if (this.name != null) + return this.name; + + var storage = DynamicEnum.GetStorage(this.GetType()); + if (!storage.CombinedNameCache.TryGetValue(this, out var combinedName)) { // Enum ToString remarks: https://learn.microsoft.com/en-us/dotnet/api/system.enum.tostring // If the FlagsAttribute is not applied to this enumerated type and there is a named constant equal to the value of this instance, then the return value is a string containing the name of the constant. // If the FlagsAttribute is applied and there is a combination of one or more named constants equal to the value of this instance, then the return value is a string containing a delimiter-separated list of the names of the constants. // Otherwise, the return value is the string representation of the numeric value of this instance. - var included = new StringBuilder(); var remain = DynamicEnum.GetValue(this); - foreach (var other in DynamicEnum.GetValues(this.GetType())) { + foreach (var other in storage.Values.Values) { if (this.HasAllFlags(other)) { var otherValue = DynamicEnum.GetValue(other); if (otherValue != 0) { @@ -113,9 +116,10 @@ namespace DynamicEnums { } } } - this.name = included.Length > 0 && remain == 0 ? included.ToString() : DynamicEnum.GetValue(this).ToString(); + combinedName = included.Length > 0 && remain == 0 ? included.ToString() : DynamicEnum.GetValue(this).ToString(); + storage.CombinedNameCache.Add(this, combinedName); } - return this.name; + return combinedName; } /// @@ -476,6 +480,7 @@ namespace DynamicEnums { public readonly Dictionary<(DynamicEnum, DynamicEnum), DynamicEnum> AndCache = new Dictionary<(DynamicEnum, DynamicEnum), DynamicEnum>(); public readonly Dictionary<(DynamicEnum, DynamicEnum), DynamicEnum> XorCache = new Dictionary<(DynamicEnum, DynamicEnum), DynamicEnum>(); public readonly Dictionary NegCache = new Dictionary(); + public readonly Dictionary CombinedNameCache = new Dictionary(); public void ClearCaches() { this.FlagCache.Clear(); @@ -484,6 +489,7 @@ namespace DynamicEnums { this.AndCache.Clear(); this.XorCache.Clear(); this.NegCache.Clear(); + this.CombinedNameCache.Clear(); } }