将枚举值与本地化字符串资源链接 [英] Linking enum value with localized string resource

查看:95
本文介绍了将枚举值与本地化字符串资源链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想要一个绑定枚举的最可维护的方法,它将本地化​​的字符串值与某个值相关联。

I want the most maintainable way of binding an enumeration and it's associated localized string values to something.

如果我将枚举和类放在同一个文件中,我觉得有点安全,但是我必须假设有一个更好的方法。我也考虑过将枚举名称与资源字符串名称相同,但我恐怕不能永远在这里执行。

If I stick the enum and the class in the same file I feel somewhat safe but I have to assume there is a better way. I've also considered having the enum name be the same as the resource string name, but I'm afraid I can't always be here to enforce that.

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;
        }
    }
}


推荐答案

您可以在每个枚举值中添加DescriptionAttribute。

You can add DescriptionAttribute to each enum value.

public enum SourceFilterOption
{
    [Description("LAST_NUMBER_OF_OCCURANCES")]
    LastNumberOccurences,
    ...
}

在需要时拉出描述(资源密钥)。

Pull out the description (resource key) when you need it.

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();
}

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

编辑:对评论的响应(@Tergiver)在我的例子中使用(现有的)DescriptionAttribute是快速完成工作,你会更好地实现自己的自定义属性,而不是在其目的之外使用一个。这样的东西:

Response to comments (@Tergiver). Using the (existing) DescriptionAttribute in my example is to get the job done quickly. You would be better implementing your own custom attribute instead of using one outside of its purpose. Something like this:

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

这篇关于将枚举值与本地化字符串资源链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆