C#中:如何使用类型转换器本地化枚举 [英] C#: How to use a Type Converter to localize enums

查看:186
本文介绍了C#中:如何使用类型转换器本地化枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解阅读的这个答案以我的其他问题之一。但我不知道我是否完全得到它...

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继承的类。然后你使用 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拥有的文档和类型转换器实现的一些例子。

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

这篇关于C#中:如何使用类型转换器本地化枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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