简体   繁体   English

将文化特定的枚举DisplayName字符串转换为枚举

[英]Converting Culture Specific Enum DisplayName String to Enum

I've created a small application, which I am now in the process of defining culture specific text for the constants on each of the pages. 我已经创建了一个小应用程序,我现在正在为每个页面上的常量定义特定于文化的文本。 I've been using a few Enum DropDownLists and have been using the Display(Name="Something") attribute for each of the Enum values for the string name to display. 我一直在使用一些Enum DropDownLists,并且已经为每个Enum值使用Display(Name="Something")属性来显示字符串名称。

Now that I'm using resource files to determine the text based on the culture I have had to change the attribute values to [Display(Name="SomeResourceValue", ResourceType=typeof(Resources.Resources))] 现在我正在使用资源文件来确定基于文化的文本我必须将属性值更改为[Display(Name="SomeResourceValue", ResourceType=typeof(Resources.Resources))]

The issue I'm having is that I had a static method that takes the string DisplayName and returns the Enum value (providing the Enum type is supplied), which now doesn't work since introducing the resource files. 我遇到的问题是我有一个静态方法,它接受字符串DisplayName并返回Enum值(提供Enum类型),自引入资源文件后现在不起作用。

The method I'm trying to improve upon is as follows: 我正在努力改进的方法如下:

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

If anyone could help me improve this to allow for a resource lookup I would be very grateful. 如果有人可以帮助我改进这个以允许资源查找,我将非常感激。

The working solution is as follows: 工作方案如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM