mirror of
https://github.com/Kareadita/Kavita.git
synced 2025-09-29 15:30:50 -04:00
Co-authored-by: DieselTech <30128380+DieselTech@users.noreply.github.com> Co-authored-by: majora2007 <josephmajora@gmail.com>
44 lines
1.2 KiB
C#
44 lines
1.2 KiB
C#
#nullable enable
|
|
using System;
|
|
using System.ComponentModel;
|
|
using System.Reflection;
|
|
|
|
namespace API.Extensions;
|
|
|
|
public static class EnumExtensions
|
|
{
|
|
/// <summary>
|
|
/// Extension on Enum.TryParse which also tried matching on the description attribute
|
|
/// </summary>
|
|
/// <returns>if a match was found</returns>
|
|
/// <remarks>First tries Enum.TryParse then fall back to the more expensive operation</remarks>
|
|
public static bool TryParse<TEnum>(string? value, out TEnum result) where TEnum : struct, Enum
|
|
{
|
|
result = default;
|
|
|
|
if (string.IsNullOrEmpty(value))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (Enum.TryParse(value, out result))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static))
|
|
{
|
|
var description = field.GetCustomAttribute<DescriptionAttribute>()?.Description;
|
|
|
|
if (!string.IsNullOrEmpty(description) &&
|
|
string.Equals(description, value, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
result = (TEnum)field.GetValue(null)!;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|