将枚举值与本地化字符串资源相链接

Joe*_*oeB 6 .net c# enums encapsulation

相关: 从枚举属性获取枚举

我希望以最可维护的方式绑定枚举,并将它与关联的本地化字符串值相关联.

如果我把枚举和类放在同一个文件中,我觉得有些安全,但我必须假设有更好的方法.我还考虑过将枚举名称与资源字符串名称相同,但我担心我不能总是在这里强制执行.

using CR = AcmeCorp.Properties.Resources;

public enum SourceFilterOption
{
    LastNumberOccurences,
    LastNumberWeeks,
    DateRange
    // if you add to this you must update FilterOptions.GetString
}

public class FilterOptions
{
    public Dictionary<SourceFilterOption, String> GetEnumWithResourceString()
    {
        var dict = new Dictionary<SourceFilterOption, String>();
        foreach (SourceFilterOption filter in Enum.GetValues(typeof(SourceFilterOption)))
        {
            dict.Add(filter, GetString(filter));
        }
        return dict;
    }

    public String GetString(SourceFilterOption option)
    {
        switch (option)
        {
            case SourceFilterOption.LastNumberOccurences:
                return CR.LAST_NUMBER_OF_OCCURANCES;
            case SourceFilterOption.LastNumberWeeks:
                return CR.LAST_NUMBER_OF_WEEKS;
            case SourceFilterOption.DateRange:
            default:
                return CR.DATE_RANGE;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ing 10

您可以将DescriptionAttribute添加到每个枚举值.

public enum SourceFilterOption
{
    [Description("LAST_NUMBER_OF_OCCURANCES")]
    LastNumberOccurences,
    ...
}
Run Code Online (Sandbox Code Playgroud)

在需要时拉出描述(资源键).

FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),     
if (attributes.Length > 0)
{
    return attributes[0].Description;
}
else
{
    return value.ToString();
}
Run Code Online (Sandbox Code Playgroud)

http://geekswithblogs.net/paulwhitblog/archive/2008/03/31/use-the-descriptionattribute-with-an-enum-to-display-status-messages.aspx

编辑:对评论的回应(@Tergiver).在我的示例中使用(现有)DescriptionAttribute是为了快速完成工作.您最好实现自己的自定义属性,而不是使用其目的之外的属性.像这样的东西:

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inheritable = false)]
public class EnumResourceKeyAttribute : Attribute
{
 public string ResourceKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)