7

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

我想要绑定枚举的最可维护的方式,并且它将本地化​​字符串值关联到某些东西。

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

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

5 回答 5

10

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

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

需要时提取描述(资源密钥)。

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 是为了快速完成工作。您最好实现自己的自定义属性,而不是使用其目的之外的属性。像这样的东西:

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inheritable = false)]
public class EnumResourceKeyAttribute : Attribute
{
 public string ResourceKey { get; set; }
}
于 2012-07-17T22:32:33.753 回答
1

如果有人没有正确更新它,你可能会立即崩溃。

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:
            return CR.DATE_RANGE;
        default:
            throw new Exception("SourceFilterOption " + option + " was not found");
    }
}
于 2012-07-18T13:28:14.107 回答
1

我通过以下方式映射到资源: 1. 使用 ctor 定义一个类 StringDescription 获取 2 个参数(资源类型及其名称)

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
class StringDescriptionAttribute : Attribute
{
    private string _name;
    public StringDescriptionAttribute(string name)
    {
        _name = name;
    }

    public StringDescriptionAttribute(Type resourseType, string name)
    {
            _name = new ResourceManager(resourseType).GetString(name);

    }
    public string Name { get { return _name; } }
}
  1. 为任一文化创建资源文件(例如 WebTexts.resx 和 Webtexts.ru.resx)。让我们成为红色,绿色等颜色......

  2. 定义枚举:

    枚举颜色{ [StringDescription(typeof(WebTexts),"Red")] Red=1 , [StringDescription(typeof(WebTexts), "Green")] Green = 2, [StringDescription(typeof(WebTexts), "Blue")] Blue = 3, [StringDescription("带有疯狂黑眼圈的 Antracit")] AntracitWithMadDarkCircles

    }

  3. 定义一个通过反射获取资源描述的静态方法

    公共静态字符串 GetStringDescription(Enum en) {

        var enumValueName = Enum.GetName(en.GetType(),en);
    
        FieldInfo fi = en.GetType().GetField(enumValueName);
    
        var attr = (StringDescriptionAttribute)fi.GetCustomAttribute(typeof(StringDescriptionAttribute));
    
        return attr != null ? attr.Name : "";
    }
    
  4. 吃 :

    颜色颜色;col = 颜色.红色; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

        var ListOfColors = typeof(Colour).GetEnumValues().Cast<Colour>().Select(p => new { Id = p, Decr = GetStringDescription(p) }).ToList();
    
        foreach (var listentry in ListOfColors)
            Debug.WriteLine(listentry.Id + " " + listentry.Decr);
    
于 2015-08-26T06:45:25.097 回答
1

有一种最简单的方法可以根据资源文件中的文化获取枚举描述值

我的枚举

  public enum DiagnosisType
    {
        [Description("Nothing")]
        NOTHING = 0,
        [Description("Advice")]
        ADVICE = 1,
        [Description("Prescription")]
        PRESCRIPTION = 2,
        [Description("Referral")]
        REFERRAL = 3

}

我已经使资源文件和密钥与枚举描述值相同

Resoucefile和Enum Key and Value Image,点击查看resouce文件图片

   public static string GetEnumDisplayNameValue(Enum enumvalue)
    {
        var name = enumvalue.ToString();
        var culture = Thread.CurrentThread.CurrentUICulture;
        var converted = YourProjectNamespace.Resources.Resource.ResourceManager.GetString(name, culture);
        return converted;
    }

在视图上调用此方法

  <label class="custom-control-label" for="othercare">YourNameSpace.Yourextenstionclassname.GetEnumDisplayNameValue(EnumHelperClass.DiagnosisType.NOTHING )</label>

它将字符串accordig返回到您的文化

于 2018-09-24T07:08:12.297 回答
0

我必须在 WPF 中使用它,这是我实现它的方式

首先你需要定义一个属性

public class LocalizedDescriptionAttribute : DescriptionAttribute
{
    private readonly string _resourceKey;
    private readonly ResourceManager _resource;
    public LocalizedDescriptionAttribute(string resourceKey, Type resourceType)
    {
        _resource = new ResourceManager(resourceType);
        _resourceKey = resourceKey;
    }

    public override string Description
    {
        get
        {
            string displayName = _resource.GetString(_resourceKey);

            return string.IsNullOrEmpty(displayName)
                ? string.Format("[[{0}]]", _resourceKey)
                : displayName;
        }
    }
}

您可以像这样使用该属性

public enum OrderType
{
    [LocalizedDescription("DineIn", typeof(Properties.Resources))]
    DineIn = 1,
    [LocalizedDescription("Takeaway", typeof(Properties.Resources))]
    Takeaway = 2
}

然后定义一个转换器

public class EnumToDescriptionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo language)
    {
        var enumValue = value as Enum;

        return enumValue == null ? DependencyProperty.UnsetValue : enumValue.GetDescriptionFromEnumValue();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language)
    {
        return value;
    }
}

然后在你的 XAML

<cr:EnumToDescriptionConverter x:Key="EnumToDescriptionConverter" />

<TextBlock Text="{Binding Converter={StaticResource EnumToDescriptionConverter}}"/>
于 2017-11-23T23:58:42.467 回答