正在将区域性特定的枚举DisplayName字符串转换为枚举

本文关键字:枚举 DisplayName 字符串 转换 区域性 | 更新日期: 2023-09-27 18:01:05

我创建了一个小型应用程序,现在正在为每个页面上的常量定义特定于区域性的文本。我一直在使用一些Enum DropDownList,并为要显示的字符串名称的每个Enum值使用Display(Name="Something")属性。

现在我使用资源文件根据区域性确定文本,我不得不将属性值更改为[Display(Name="SomeResourceValue", ResourceType=typeof(Resources.Resources))]

我遇到的问题是,我有一个静态方法,它接受字符串DisplayName并返回Enum值(提供Enum类型(,自从引入资源文件以来,它现在不起作用。

我试图改进的方法如下:

//Converts Enum DisplayName attribute text to it's Enum value 
    public static T GetEnumDisplayNameValue<T>(this string name)
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException();
        FieldInfo[] fields = type.GetFields();
        var field = fields
                        .SelectMany(f => f.GetCustomAttributes(
                            typeof(DisplayAttribute), false), (
                                f, a) => new { Field = f, Att = a }).SingleOrDefault(a => ((DisplayAttribute)a.Att)
                            .Name == name);
        return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
    }

如果有人能帮助我改进这一点,以便进行资源查找,我将不胜感激。

正在将区域性特定的枚举DisplayName字符串转换为枚举

工作解决方案如下:

    public static T GetEnumDisplayNameValue<T>(this string name, CultureInfo culture)
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException();
        FieldInfo[] fields = type.GetFields();
        var field = fields.SelectMany(f => f.GetCustomAttributes(typeof(DisplayAttribute), false),
            (f, a) => new { Field = f, Att = a })
            .SingleOrDefault(a => Resources.ResourceManager.GetString(((DisplayAttribute)a.Att).Name, culture) == name);
        return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
    }