C#:如何使用类型转换器来本地化枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1117961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:36:50  来源:igfitidea点击:

C#: How to use a Type Converter to localize enums

c#localizationenumstypeconverter

提问by Svish

I'm trying to understand how to use Type Converters after reading this answerto one of my other questions. But I'm not sure if I quite get it...

在阅读了我的其他问题之一的答案后,我试图了解如何使用类型转换器。但我不确定我是否完全明白......

In my particular case I would like to "convert" an enum member into a localized string by getting a resource string depending on what enum member it is. So for example if I had this enum:

在我的特定情况下,我想通过根据枚举成员的类型获取资源字符串,将枚举成员“转换”为本地化字符串。例如,如果我有这个枚举:

public enum Severity
{
    Critical,
    High,
    Medium,
    Low
}

or this:

或这个:

public enum Color
{
    Black = 0x0,
    Red = 0x1,
    Green = 0x2,
    Blue = 0x4,
    Cyan = Green | Blue,
    Magenta = Red | Blue,
    Yellow = Red | Green,
    White = Red | Green | Blue,
}

How would I create a Type Converter that could convert those members into localized strings? And how would I use it? Currently I would need to use it in a WinForms application, but more general examples are welcome as well.

我将如何创建一个可以将这些成员转换为本地化字符串的类型转换器?我将如何使用它?目前我需要在 WinForms 应用程序中使用它,但也欢迎更一般的示例。

采纳答案by womp

To create a TypeConverter, simply create a class that inherits from TypeConverter. Then you use the TypeConverterAttributeto tag your class, so that anytime someone tries a convert operation on your class, your TypeConverter is invoked.

要创建 TypeConverter,只需创建一个继承自 TypeConverter 的类。然后您使用TypeConverterAttribute来标记您的类,以便任何时候有人尝试对您的类进行转换操作时,都会调用您的 TypeConverter。

Once you inherit from TypeConverter, you should override some of its methods to do what you want. You'd probably want to look at ConvertFrom(), ConvertTo(), and ConvertToString() to start with - that's where you would implement the logic to pull out your localized version of your strings.

一旦你从 TypeConverter 继承,你应该覆盖它的一些方法来做你想做的事。您可能希望首先查看 ConvertFrom()、ConvertTo() 和 ConvertToString() - 这就是您将实现逻辑以提取字符串的本地化版本的地方。

To use your TypeConverter, you would code something like this:

要使用您的 TypeConverter,您可以编写如下代码:

var foo = TypeDescriptor.GetConverter(typeof(T));
var mystring = foo.ConvertToString(myObject));

MSDN of course has the documentation and some examplesof TypeConverter implementation.

MSDN 当然有TypeConverter 实现的文档和一些示例

回答by Steven Sudit

I believe this was already answered in How do I override ToString in C# enums?

我相信这已经在How do I override ToString in C# enums? 中得到了回答

Also, you could combine this with an extension method for enums with a name like ToDisplayString.

此外,您可以将其与名称如 ToDisplayString 的枚举的扩展方法结合使用。