C#:如何使用类型转换器来本地化枚举 [英] C#: How to use a Type Converter to localize enums
问题描述
我想了解如何在阅读这个答案我的其他问题之一。但我不知道我是否得到它...
I'm trying to understand how to use Type Converters after reading this answer to 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
}
或此:
public enum Color
{
Black = 0x0,
Red = 0x1,
Green = 0x2,
Blue = 0x4,
Cyan = Green | Blue,
Magenta = Red | Blue,
Yellow = Red | Green,
White = Red | Green | Blue,
}
如何创建可以将这些成员转换为本地化的类型转换器字符串?我该怎么用呢?目前,我需要在WinForms应用程序中使用它,但更为一般的例子也是受欢迎的。
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.
推荐答案
创建一个TypeConverter ,只需创建一个继承自TypeConverter的类。然后,您可以使用 TypeConverterAttribute 来标记您的课程,因此任何时候有人在你的班上尝试一个转换操作,你的TypeConverter被调用。
To create a TypeConverter, simply create a class that inherits from TypeConverter. Then you use the TypeConverterAttribute to tag your class, so that anytime someone tries a convert operation on your class, your TypeConverter is invoked.
一旦你继承了TypeConverter,你应该重写一些方法来做你想要的。你可能想看看ConvertFrom(),ConvertTo()和ConvertToString()开始 - 这就是你实现逻辑来拉出本地化版本的字符串的地方。
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,您可以这样编码:
To use your TypeConverter, you would code something like this:
var foo = TypeDescriptor.GetConverter(typeof(T));
var mystring = foo.ConvertToString(myObject));
MSDN当然有文档和一些TypeConverter实现的例子。
MSDN of course has the documentation and some examples of TypeConverter implementation.
这篇关于C#:如何使用类型转换器来本地化枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!