-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathEnumExtensions.cs
More file actions
64 lines (57 loc) · 2.4 KB
/
EnumExtensions.cs
File metadata and controls
64 lines (57 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
namespace Microsoft.OpenApi
{
/// <summary>
/// Enumeration type extension methods.
/// </summary>
public static class EnumExtensions
{
// Cache to store display names of enum values
private static readonly ConcurrentDictionary<Enum, string> DisplayNameCache = new();
/// <summary>
/// Gets an attribute on an enum field value.
/// </summary>
/// <typeparam name="T">The type of the attribute to retrieve.</typeparam>
/// <param name="enumValue">The enum value.</param>
/// <returns>
/// The attribute of the specified type or null.
/// </returns>
[UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Fields are never trimmed for enum types.")]
public static T? GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
{
var type = enumValue.GetType();
// Use GetField to get the field info for the enum value
var memInfo = type.GetField(enumValue.ToString(), BindingFlags.Public | BindingFlags.Static);
if (memInfo == null)
return null;
// Retrieve the custom attributes of type T
var attributes = memInfo.GetCustomAttributes<T>(false);
return attributes.FirstOrDefault();
}
/// <summary>
/// Gets the enum display name.
/// </summary>
/// <param name="enumValue">The enum value.</param>
/// <returns>
/// Use <see cref="DisplayAttribute"/> if it exists.
/// Otherwise, use the standard string representation.
/// </returns>
public static string GetDisplayName(this Enum enumValue)
{
// Retrieve the display name from the cache if it exists
return DisplayNameCache.GetOrAdd(enumValue, e =>
{
// Get the DisplayAttribute
var attribute = e.GetAttributeOfType<DisplayAttribute>();
// Return the DisplayAttribute name if it exists, otherwise return the enum's string representation
return attribute?.Name is not null ? attribute.Name : e.ToString();
});
}
}
}