如何将表示C#枚举值的字符串进行国际化? [英] How can I internationalize strings representing C# enum values?

查看:849
本文介绍了如何将表示C#枚举值的字符串进行国际化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到许多关于将字符串映射到枚举的问题和答案,反之亦然,但是如何将一系列本地化字符串映射到枚举?

I've seen many questions and answers about mapping strings to enums and vice-versa, but how can I map a series of localized strings to enums?

我只是创建一个这样的扩展方法,从资源文件返回正确的字符串?是否有一种方法来本地化这样的解决方案中的属性(如说明) ?

Should I just create an extension method like this that returns the proper string from a resource file? Is there a way to localize attributes (like "Description") that are used in solutions like this?

哪个是首选解决方案 - 扩展方法或属性。在我看来,这不是属性的预期目的。事实上,现在我想到了,如果我使用一个扩展方法,一个属性就像我用来在本地化字符串的资源文件中指定一个键来代替枚举值。

Which is the preferred solution - extension method or attributes. It seems to me that this isn't the intended purpose of attributes. In fact, now that I think about it, if I were to use an extension method an attribute seems like something I'd use to specify a key in a resource file for the localized string I want to use in place of the enum value.

编辑 - 例如:

鉴于以下枚举,

public enum TransactionTypes {
    Cheque = 1,
    BankTransfer = 2,
    CreditCard = 3
}

我想要一种将每种类型映射到本地化字符串的方法。我开始使用枚举的扩展方法,它使用switch语句和强类型的资源文件引用。

I would like a way to map each type to a localized string. I started off with an extension method for the enum that uses a switch statement and strongly typed references to the resource file.

然而,每个枚举的扩展方法不好像是一个很好的解决方案我已经开始遵循为每个枚举值创建自定义属性。该属性具有包含本地化字符串的资源文件的基本名称和密钥。在上面的枚举中,例如,我有这样的:

However, an extension method for every enum doesn't seem like a great solution. I've started following this to create a custom attribute for each enumerated value. The attribute has a base name and key for the resource file containing localized strings. In the above enum, for example, I have this:

...
[EnumResourceAttribute("FinancialTransaction", "Cheque")]
Cheque = 1,
...

FinanacialTransaction是resx文件,Check是字符串键。我正在尝试创建一个实用程序方法,我可以从任何枚举传递任何值,并返回该值的本地化字符串表示形式,假定指定了自定义属性。我不知道如何动态地访问资源文件和其中的一个密钥。

Where "FinanacialTransaction" is the resx file and "Cheque" is the string key. I'm trying to create a utility method to which I could pass any value from any enumeration and have it return the localized string representation of that value, assuming the custom attribute is specified. I just can't figure out how to dynamically access a resource file and a key within it.

推荐答案

我继续使用自定义属性并创建此实用程序方法:

I continued with the custom attributes and created this utility method:

    public static string getEnumResourceString(Enum value)
    {
        System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());
        EnumResourceAttribute attr = (EnumResourceAttribute)System.Attribute.GetCustomAttribute(fi, typeof(EnumResourceAttribute));
        return (string)HttpContext.GetGlobalResourceObject(attr.BaseName, attr.Key);
    }

这篇关于如何将表示C#枚举值的字符串进行国际化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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