File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ using System ;
2+ using System . ComponentModel . DataAnnotations ;
3+ using System . Linq ;
4+ using System . Reflection ;
5+
6+ namespace NetChris . Core ;
7+
8+ // https://stackoverflow.com/a/25109103/208990
9+ /// <summary>
10+ ///
11+ /// </summary>
12+ public static class EnumExtensions
13+ {
14+ /// <summary>
15+ /// A generic extension method that aids in reflecting
16+ /// and retrieving any attribute that is applied to an `Enum`.
17+ /// </summary>
18+ /// <seealso href="https://stackoverflow.com/a/25109103/208990" />
19+ public static TAttribute ? GetAttribute < TAttribute > ( this Enum enumValue )
20+ where TAttribute : Attribute
21+ {
22+ return enumValue . GetType ( )
23+ . GetMember ( enumValue . ToString ( ) )
24+ . First ( )
25+ . GetCustomAttribute < TAttribute > ( ) ;
26+ }
27+
28+ /// <summary>
29+ /// Get the <see cref="DisplayAttribute.Name"/> value from an enum value.
30+ /// </summary>
31+ public static string GetDisplayName ( this Enum enumValue )
32+ {
33+ string result ;
34+ var attribute = enumValue . GetAttribute < DisplayAttribute > ( ) ;
35+
36+ if ( attribute ? . Name == null )
37+ {
38+ result = enumValue . ToString ( ) ;
39+ }
40+ else
41+ {
42+ result = attribute . Name ;
43+ }
44+
45+ return result ;
46+ }
47+ }
Original file line number Diff line number Diff line change 2323 <SupportedPlatform Include =" browser" />
2424 </ItemGroup >
2525
26+ <ItemGroup >
27+ <PackageReference Include =" System.ComponentModel.Annotations" Version =" 5.0.0" />
28+ </ItemGroup >
29+
2630 <ItemGroup >
2731 <None Include =" Package-README.md" >
2832 <PackagePath >/</PackagePath >
You can’t perform that action at this time.
0 commit comments