1
1
// Copyright (c) Microsoft Corporation. All rights reserved.
2
2
// Licensed under the MIT license.
3
-
4
3
using System ;
4
+ using System . Collections . Concurrent ;
5
5
using System . Diagnostics . CodeAnalysis ;
6
6
using System . Reflection ;
7
7
using Microsoft . OpenApi . Attributes ;
@@ -13,6 +13,8 @@ namespace Microsoft.OpenApi.Extensions
13
13
/// </summary>
14
14
public static class StringExtensions
15
15
{
16
+ private static readonly ConcurrentDictionary < Type , ConcurrentDictionary < string , object > > EnumDisplayCache = new ( ) ;
17
+
16
18
/// <summary>
17
19
/// Gets the enum value based on the given enum type and display name.
18
20
/// </summary>
@@ -21,22 +23,28 @@ public static class StringExtensions
21
23
{
22
24
var type = typeof ( T ) ;
23
25
if ( ! type . IsEnum )
24
- {
25
26
return default ;
26
- }
27
+
28
+ var displayMap = EnumDisplayCache . GetOrAdd ( type , _ => new ConcurrentDictionary < string , object > ( StringComparer . OrdinalIgnoreCase ) ) ;
29
+
30
+ if ( displayMap . TryGetValue ( displayName , out var cachedValue ) )
31
+ return ( T ) cachedValue ;
32
+
27
33
28
34
foreach ( var field in type . GetFields ( BindingFlags . Public | BindingFlags . Static ) )
29
35
{
30
- var displayAttribute = ( DisplayAttribute ) field . GetCustomAttribute ( typeof ( DisplayAttribute ) ) ;
31
- if ( displayAttribute != null && displayAttribute . Name == displayName )
36
+ var displayAttribute = field . GetCustomAttribute < DisplayAttribute > ( ) ;
37
+ if ( displayAttribute != null && displayAttribute . Name . Equals ( displayName , StringComparison . OrdinalIgnoreCase ) )
32
38
{
33
- return ( T ) field . GetValue ( null ) ;
39
+ var enumValue = ( T ) field . GetValue ( null ) ;
40
+ displayMap . TryAdd ( displayName , enumValue ) ;
41
+ return enumValue ;
34
42
}
35
43
}
36
44
37
45
return default ;
38
46
}
39
47
internal static string ToFirstCharacterLowerCase ( this string input )
40
- => string . IsNullOrEmpty ( input ) ? string . Empty : char . ToLowerInvariant ( input [ 0 ] ) + input . Substring ( 1 ) ;
48
+ => string . IsNullOrEmpty ( input ) ? string . Empty : char . ToLowerInvariant ( input [ 0 ] ) + input . Substring ( 1 ) ;
41
49
}
42
50
}
0 commit comments