2
2
// Licensed under the MIT license.
3
3
4
4
using System ;
5
+ using System . Collections . Concurrent ;
5
6
using System . Diagnostics . CodeAnalysis ;
6
7
using System . Linq ;
7
8
using System . Reflection ;
@@ -14,6 +15,9 @@ namespace Microsoft.OpenApi.Extensions
14
15
/// </summary>
15
16
public static class EnumExtensions
16
17
{
18
+ // Cache to store display names of enum values
19
+ private static readonly ConcurrentDictionary < Enum , string > DisplayNameCache = new ( ) ;
20
+
17
21
/// <summary>
18
22
/// Gets an attribute on an enum field value.
19
23
/// </summary>
@@ -26,7 +30,13 @@ public static class EnumExtensions
26
30
public static T GetAttributeOfType < T > ( this Enum enumValue ) where T : Attribute
27
31
{
28
32
var type = enumValue . GetType ( ) ;
33
+ // Use GetField to get the field info for the enum value
29
34
var memInfo = type . GetField ( enumValue . ToString ( ) , BindingFlags . Public | BindingFlags . Static ) ;
35
+
36
+ if ( memInfo == null )
37
+ return null ;
38
+
39
+ // Retrieve the custom attributes of type T
30
40
var attributes = memInfo . GetCustomAttributes < T > ( false ) ;
31
41
return attributes . FirstOrDefault ( ) ;
32
42
}
@@ -36,13 +46,20 @@ public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
36
46
/// </summary>
37
47
/// <param name="enumValue">The enum value.</param>
38
48
/// <returns>
39
- /// Use <see cref="DisplayAttribute"/> if exists.
49
+ /// Use <see cref="DisplayAttribute"/> if it exists.
40
50
/// Otherwise, use the standard string representation.
41
51
/// </returns>
42
52
public static string GetDisplayName ( this Enum enumValue )
43
53
{
44
- var attribute = enumValue . GetAttributeOfType < DisplayAttribute > ( ) ;
45
- return attribute == null ? enumValue . ToString ( ) : attribute . Name ;
54
+ // Retrieve the display name from the cache if it exists
55
+ return DisplayNameCache . GetOrAdd ( enumValue , e =>
56
+ {
57
+ // Get the DisplayAttribute
58
+ var attribute = e . GetAttributeOfType < DisplayAttribute > ( ) ;
59
+
60
+ // Return the DisplayAttribute name if it exists, otherwise return the enum's string representation
61
+ return attribute == null ? e . ToString ( ) : attribute . Name ;
62
+ } ) ;
46
63
}
47
64
}
48
65
}
0 commit comments