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

前端 未结 2 876
温柔的废话
温柔的废话 2021-01-05 07:19

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

相关标签:
2条回答
  • 2021-01-05 07:29

    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.

    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.

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

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

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

    0 讨论(0)
  • 2021-01-05 07:41

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

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

    0 讨论(0)
提交回复
热议问题