28 lines
830 B
C#
28 lines
830 B
C#
using System;
|
|
using System.Linq;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace GerstITS.Examples.Api.Configurations;
|
|
|
|
public static class IConfigurationExtensions
|
|
{
|
|
#region Methods
|
|
|
|
public static TEnum GetFlaggedEnum<TEnum>(this IConfiguration configuration, string key)
|
|
where TEnum : struct, IConvertible
|
|
{
|
|
ThrowsAnExceptionIfTypeIsNotAnEnumeration<TEnum>();
|
|
|
|
return (TEnum)(object)(configuration.GetSection(key)?
|
|
.Get<TEnum[]>() ?? Enumerable.Empty<TEnum>())
|
|
.Sum(i => (int)(object)i);
|
|
}
|
|
|
|
private static void ThrowsAnExceptionIfTypeIsNotAnEnumeration<TEnum>() where TEnum : struct, IConvertible
|
|
{
|
|
if (!typeof(TEnum).IsEnum)
|
|
throw new InvalidOperationException($"{typeof(TEnum)} is not supported.");
|
|
}
|
|
|
|
#endregion
|
|
} |