使用枚举类保持枚举到对象的映射
本文关键字:枚举 对象 映射 | 更新日期: 2023-09-27 18:32:05
我经常需要一个枚举和另一个对象(本例中的字符串)之间的全局硬编码映射。我想共同定位枚举和映射定义以阐明维护。
如您所见,在此示例中,创建了一个具有一个静态字段的烦人的类。
public enum EmailTemplates
{
// Remember to edit the corresponding mapping singleton!
WelcomeEmail,
ConfirmEmail
}
public class KnownTemplates
{
public static Dictionary<EmailTemplates, string> KnownTemplates;
static KnownTemplates() {
KnownTemplates.Add(EmailTemplates.WelcomeEmail, "File1.htm");
KnownTemplates.Add(EmailTemplates.ConfirmEmail, "File2.htm");
}
}
有时,映射类可以具有更多功能和有意义的名称,并且映射活动甚至可以是私有的。但这只会污染维护/关联问题。
有人对此有很好的模式吗?
可以使用属性来批注枚举,然后使用反射来生成字典。
[AttributeUsage(AttributeTargets.Field)]
sealed class TemplateAttribute : Attribute {
public TemplateAttribute(String fileName) {
FileName = fileName;
}
public String FileName { get; set; }
}
enum EmailTemplate {
[Template("File1.htm")]
WelcomeEmail,
[Template("File2.htm")]
ConfirmEmail
}
class KnownTemplates {
static Dictionary<EmailTemplate, String> knownTemplates;
static KnownTemplates() {
knownTemplates = typeof(EmailTemplates)
.GetFields(BindingFlags.Static | BindingFlags.Public)
.Where(fieldInfo => Attribute.IsDefined(fieldInfo, typeof(TemplateAttribute)))
.Select(
fieldInfo => new {
Value = (EmailTemplate) fieldInfo.GetValue(null),
Template = (TemplateAttribute) Attribute
.GetCustomAttribute(fieldInfo, typeof(TemplateAttribute))
}
)
.ToDictionary(x => x.Value, x => x.Template.FileName);
}
}
如果您经常这样做,则可以创建一个更通用的泛型函数,该函数将枚举值与与该枚举值关联的属性组合在一起:
static IEnumerable<Tuple<TEnum, TAttribute>> GetEnumAttributes<TEnum, TAttribute>()
where TEnum : struct
where TAttribute : Attribute {
return typeof(TEnum)
.GetFields(BindingFlags.Static | BindingFlags.Public)
.Where(fieldInfo => Attribute.IsDefined(fieldInfo, typeof(TAttribute)))
.Select(
fieldInfo => Tuple.Create(
(TEnum) fieldInfo.GetValue(null),
(TAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof(TAttribute))
)
);
}
并像这样使用它:
knownTemplates = GetEnumAttributes<EmailTemplate, TemplateAttribute>()
.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2.FileName);
为了获得更多乐趣,您可以创建一个扩展方法:
static class EmailTemplateExtensions {
static Dictionary<EmailTemplate, String> templates;
static EmailTemplateExtensions() {
templates = GetEnumAttributes<EmailTemplate, TemplateAttribute>()
.ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2.FileName);
}
public static String FileName(this EmailTemplate emailTemplate) {
String fileName;
if (templates.TryGetValue(emailTemplate, out fileName))
return fileName;
throw new ArgumentException(
String.Format("No template defined for EmailTemplate.{0}.", emailTemplate)
);
}
}
然后调用EmailTemplate.ConfirmEmail.FileName()
将返回File2.htm
。
这是一种对我来说非常有效的方法。
public class BaseErrWarn : Attribute
{
public string Code { get; set; }
public string Description { get; set; }
public BaseErrWarn(string code, string description)
{
this.Code = code;
this.Description = description;
}
}
public enum ErrorCode
{
[BaseErrWarn("ClientErrMissingOrEmptyField", "Field was missing or empty.")] ClientErrMissingOrEmptyField,
[BaseErrWarn("ClientErrInvalidFieldValue", "Not a valid field value.")] ClientErrInvalidFieldValue,
[BaseErrWarn("ClientErrMissingValue", "No value passed in.")] ClientErrMissingValue
}
现在,您可以使用反射将枚举映射到 BaseErrWarn 类:
public static BaseErrWarn GetAttribute(Enum enumVal)
{
return (BaseErrWarn)Attribute.GetCustomAttribute(ForValue(enumVal), typeof(BaseErrWarn));
}
private static MemberInfo ForValue(Enum errorEnum)
{
return typeof(BaseErrWarn).GetField(Enum.GetName(typeof(BaseErrWarn), errorEnum));
}
下面是一个示例,它使用此映射将枚举映射到对象,然后从中提取字段:
public BaseError(Enum errorCode)
{
BaseErrWarn baseError = GetAttribute(errorCode);
this.Code = baseError.Code;
this.Description = baseError.Description;
}
public BaseError(Enum errorCode, string fieldName)
{
BaseErrWarn baseError = GetAttribute(errorCode);
this.Code = baseError.Code;
this.Description = baseError.Description;
this.FieldName = fieldName;
}
通常,当您想向枚举元素添加额外的信息或行为时,这意味着您需要一个完整的类。你可以从(旧)Java借用类型安全的枚举模式,并创建如下的东西:
sealed class EmailTemplate {
public static readonly EmailTemplate Welcome = new EmailTemplate("File1.html");
public static readonly EmailTemplate Confirm = new EmailTemplate("File2.html");
private EmailTemplate(string location) {
Location = location;
}
public string Location { get; private set; }
public string Render(Model data) { ... }
}
现在,您可以将任何属性或方法与元素相关联,如上面的Location
和Render
。