使用 EnumMemberAttribute 并执行自动字符串转换
本文关键字:字符串 转换 执行 EnumMemberAttribute 使用 | 更新日期: 2023-09-27 18:33:09
>我有以下代码
[DataContract]
public enum StatusType
{
[EnumMember(Value = "A")]
All,
[EnumMember(Value = "I")]
InProcess,
[EnumMember(Value = "C")]
Complete,
}
我想做以下几点:
var s = "C";
StatusType status = SerializerHelper.ToEnum<StatusType>(s); //status is now StatusType.Complete
string newString = SerializerHelper.ToEnumString<StatusType>(status); //newString is now "C"
我已经使用 DataContractSerializer 完成了第二部分(请参阅下面的代码),但这似乎需要做很多工作。
我错过了一些明显的东西吗?想法?谢谢。
public static string ToEnumString<T>(T type)
{
string s;
using (var ms = new MemoryStream())
{
var ser = new DataContractSerializer(typeof(T));
ser.WriteObject(ms, type);
ms.Position = 0;
var sr = new StreamReader(ms);
s = sr.ReadToEnd();
}
using (var xml = new XmlTextReader(s, XmlNodeType.Element, null))
{
xml.MoveToContent();
xml.Read();
return xml.Value;
}
}
这是我的主张 - 它应该给你如何做到这一点的想法(另检查获取 Enum 值的属性):
public static string ToEnumString<T>(T type)
{
var enumType = typeof (T);
var name = Enum.GetName(enumType, type);
var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
return enumMemberAttribute.Value;
}
public static T ToEnum<T>(string str)
{
var enumType = typeof(T);
foreach (var name in Enum.GetNames(enumType))
{
var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
}
//throw exception or whatever handling you want or
return default(T);
}
如果你的项目引用了Newtonsoft.Json(现在什么没有?!),那么有一个简单的单行解决方案不需要反思:
public static string ToEnumString<T>(T value)
{
return JsonConvert.SerializeObject(value).Replace("'"", "");
}
public static T ToEnum<T>(string value)
{
return JsonConvert.DeserializeObject<T>($"'"{value}'"");
}
ToEnumString
方法仅在JsonSerializerSettings
中注册了StringEnumConverter
时才有效(请参阅 JavaScriptSerializer - JSON 枚举序列化为字符串),例如
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = { new StringEnumConverter() }
};
此方法的另一个优点是,如果只有一些枚举元素具有 member 属性,则事情仍然可以按预期工作,例如
public enum CarEnum
{
Ford,
Volkswagen,
[EnumMember(Value = "Aston Martin")]
AstonMartin
}
使用扩展和 C# 7.3 约束
public static class EnumMemberExtensions
{
public static string ToEnumString<T>(this T type)
where T : Enum
{
var enumType = typeof(T);
var name = Enum.GetName(enumType, type);
var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
return enumMemberAttribute.Value;
}
public static T ToEnum<T>(this string str)
where T : Enum
{
var enumType = typeof(T);
foreach (var name in Enum.GetNames(enumType))
{
var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
}
//throw exception or whatever handling you want or
return default;
}
}
您可以使用反射来获取EnumMemberAttribute
的值。
public static string ToEnumString<T>(T instance)
{
if (!typeof(T).IsEnum)
throw new ArgumentException("instance", "Must be enum type");
string enumString = instance.ToString();
var field = typeof(T).GetField(enumString);
if (field != null) // instance can be a number that was cast to T, instead of a named value, or could be a combination of flags instead of a single value
{
var attr = (EnumMemberAttribute)field.GetCustomAttributes(typeof(EnumMemberAttribute), false).SingleOrDefault();
if (attr != null) // if there's no EnumMember attr, use the default value
enumString = attr.Value;
}
return enumString;
}
根据您的ToEnum
的工作方式,您可能还希望在那里使用这种方法。 此外,在调用ToEnumString
时可以推断出类型,例如 SerializerHelper.ToEnumString(status);
此示例演示如何使用 DescriptionAttribute
、EnumMemberAttribute
和属性名称转换枚举:
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
public static class EnumExtensions
{
public static T ToEnumByAttributes<T>(this string value)
where T:Enum
{
var enumType = typeof(T);
foreach (var name in Enum.GetNames(enumType))
{
var field = enumType.GetField(name);
if(field == null) continue;
var enumMemberAttribute = GetEnumMemberAttribute(field);
if (enumMemberAttribute != null && enumMemberAttribute.Value == value)
{
return (T)Enum.Parse(enumType, name);
}
var descriptionAttribute = GetDescriptionAttribute(field);
if (descriptionAttribute != null && descriptionAttribute.Description == value)
{
return (T)Enum.Parse(enumType, name);
}
if (name == value)
{
return (T)Enum.Parse(enumType, name);
}
}
throw new ArgumentOutOfRangeException(nameof(value), value, $"The value could not be mapped to type {enumType.FullName}");
}
public static string ToStringByAttributes(this Enum value)
{
var field = value
.GetType()
.GetField(value.ToString());
if (field == null) return string.Empty;
var enumMemberAttribute = GetEnumMemberAttribute(field);
if (enumMemberAttribute != null)
{
return enumMemberAttribute.Value ?? string.Empty;
}
var descriptionAttribute = GetDescriptionAttribute(field);
if (descriptionAttribute != null)
{
return descriptionAttribute.Description;
}
return value.ToString();
}
private static DescriptionAttribute? GetDescriptionAttribute(FieldInfo field)
{
return field
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.OfType<DescriptionAttribute>()
.SingleOrDefault();
}
private static EnumMemberAttribute? GetEnumMemberAttribute(FieldInfo field)
{
return field
.GetCustomAttributes(typeof(EnumMemberAttribute), false)
.OfType<EnumMemberAttribute>()
.SingleOrDefault();
}
}
NUnit测试:
[TestFixture]
public sealed class EnumExtensionsTests
{
public enum TestEnum
{
[EnumMember(Value = "A")]
Alpha,
[Description("O")]
Omega
}
[Test]
public void ShouldSerialize_FromEnumAttribute()
{
var result = TestEnum.Alpha.ToStringByAttributes();
Assert.That(result, Is.EqualTo("A"));
}
[Test]
public void ShouldSerialize_FromDescriptionAttribute()
{
var result = TestEnum.Omega.ToStringByAttributes();
Assert.That(result, Is.EqualTo("O"));
}
[Test]
public void ShouldDeserialize_FromEnumAttribute()
{
var result = "A".ToEnumByAttributes<TestEnum>();
Assert.That(result, Is.EqualTo(TestEnum.Alpha));
}
[Test]
public void ShouldDeserialize_FromDescriptionAttribute()
{
var result = "O".ToEnumByAttributes<TestEnum>();
Assert.That(result, Is.EqualTo(TestEnum.Omega));
}
[Test]
public void ShouldDeserialize_FromPropertyName()
{
var result = "Alpha".ToEnumByAttributes<TestEnum>();
Assert.That(result, Is.EqualTo(TestEnum.Alpha));
}
}