-
-
Notifications
You must be signed in to change notification settings - Fork 148
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for enum name sources (EnumMemberAttribute and DescriptionAttribute) #1079
Comments
The enum mapping strategies are currently used to map from one enum to another enum. |
Yes, you're correct, I didn't think the |
We thought about allowing the Would be happy to accept a PR implementing this 😊 |
#1235 is asking for support of |
I have a need for this. The use case is like: public enum IanaTimeZone
{
[EnumMember(Value = "Africa/Abidjan")] AfricaAbidjan,
[EnumMember(Value = "Africa/Algiers")] AfricaAlgiers,
[EnumMember(Value = "Africa/Bissau")] AfricaBissau,
[EnumMember(Value = "Africa/Cairo")] AfricaCairo,
//......
} In the meantime we have the following converter being used. EnumMemberValue use is unfortunately not AOT compatible just yet, but coming soon in .NET 9 via dotnet/runtime#74385. I believe this provides slightly more impetus for adding support of the EnumMember attribute to Mapperly. private static IanaTimeZone StringToIanaTimeZone(string s) => EnumMemberValueConverter.ToEnum<IanaTimeZone>(s);
private static string IanaTimeZoneToString(IanaTimeZone t) => EnumMemberValueConverter.ToString<IanaTimeZone>(t); public static class EnumMemberValueConverter
{
public static TEnum? ToEnum<TEnum>(string value) where TEnum : Enum
{
foreach (var field in typeof(TEnum).GetFields())
{
var attribute = field.GetCustomAttribute<EnumMemberAttribute>();
if (attribute != null && attribute.Value == value)
{
return (TEnum)field.GetValue(null)!;
}
}
throw new ArgumentException($"No EnumMember with value '{value}' found in {typeof(TEnum).Name}", value);
}
public static string ToString<TEnum>(TEnum enumValue) where TEnum : Enum
{
var field = typeof(TEnum).GetField(enumValue.ToString());
if (field == null)
{
throw new ArgumentException($"No field found for value '{enumValue}' in enum {typeof(TEnum).Name}", enumValue.ToString());
}
var attribute = field.GetCustomAttribute<EnumMemberAttribute>();
return attribute is { Value: not null } ? attribute.Value : enumValue.ToString();
}
} |
EnumMember
enables control of the names of the enumerations as they are serialized, e.g.from https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.enummemberattribute?view=net-8.0
It would be great if those annotations could be used to map to and from strings, e.g. by changing the mapping strategy
EnumMappingStrategy = EnumMappingStrategy.ByAnnotation
.The text was updated successfully, but these errors were encountered: