refactor: ♻️ enum 扩展方法

This commit is contained in:
tk 2024-12-07 15:26:50 +08:00 committed by nsnail
parent 194eb89d31
commit 89846d9783
5 changed files with 23 additions and 13 deletions

View File

@ -0,0 +1,16 @@
namespace NetAdmin.Infrastructure.Enums;
/// <summary>
/// 枚举扩展方法
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// 通过类泛型类型获取特性
/// </summary>
public static T Attr<T>(this Enum me)
where T : Attribute
{
return me.GetType().GetMember(me.ToString())[0].GetCustomAttributes<T>(false).FirstOrDefault();
}
}

View File

@ -1,6 +1,4 @@
using Microsoft.OpenApi.Extensions;
namespace NetAdmin.Infrastructure.Extensions;
namespace NetAdmin.Infrastructure.Extensions;
/// <summary>
/// CountryCodes 扩展方法
@ -12,6 +10,6 @@ public static class CountryCodesExtensions
/// </summary>
public static int GetCallingCode(this CountryCodes me)
{
return me.GetAttributeOfType<CountryInfoAttribute>().CallingCode;
return me.Attr<CountryInfoAttribute>().CallingCode;
}
}

View File

@ -1,5 +1,3 @@
using Microsoft.OpenApi.Extensions;
namespace NetAdmin.Infrastructure.Utils;
/// <summary>
@ -15,13 +13,13 @@ public static class PhoneNumberHelper
{
_countryList = Enum.GetValues<CountryCodes>()
.SelectMany(x => {
var attribute = x.GetAttributeOfType<CountryInfoAttribute>();
var attribute = x.Attr<CountryInfoAttribute>();
// ReSharper disable once UseCollectionExpression
return (attribute.CallingSubCode ?? new[] { string.Empty }).Select(y => (attribute.CallingCode + y, x));
})
.OrderBy(x => x.Item1)
.ThenByDescending(x => x.x.GetAttributeOfType<CountryInfoAttribute>().IsPreferred)
.ThenByDescending(x => x.x.Attr<CountryInfoAttribute>().IsPreferred)
.DistinctBy(x => x.Item1)
.OrderByDescending(x => x.Item1.Length);
}

View File

@ -1,6 +1,5 @@
using NetAdmin.Domain.Dto.Sys.UserProfile;
// ReSharper disable once CheckNamespace
namespace NetAdmin.SysComponent.Application.Modules.Sys;
public partial interface IUserModule

View File

@ -1,4 +1,3 @@
using Microsoft.OpenApi.Extensions;
using NetAdmin.Domain.Attributes;
namespace NetAdmin.SysComponent.Application.Services.Sys;
@ -32,11 +31,11 @@ public sealed class ConstantService : ServiceBase<IConstantService>, IConstantSe
static string[] GetDicValue(Enum y)
{
var ret = new[] { Convert.ToInt64(y, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture), y.ResDesc<Ln>() };
if (y is CountryCodes) {
return [..ret, y.GetAttributeOfType<CountryInfoAttribute>().CallingCode.ToInvString()];
if (y is CountryCodes z) {
return [..ret, z.GetCallingCode().ToInvString()];
}
var indicate = y.GetAttributeOfType<IndicatorAttribute>()?.Indicate.ToLowerInvariant();
var indicate = y.Attr<IndicatorAttribute>()?.Indicate.ToLowerInvariant();
return indicate.NullOrEmpty() ? ret : [..ret, indicate];
}