I would like to display Yes/No in different languages according to some boolean variable.
Is there a generic way to format it according to the locale passed to it?
If there isn't, what is the standard way to format a boolean besides boolVar ? Resources.Yes : Resources.No
.
I'm guessing that boolVar.ToString(IFormatProvider)
is involved.
Is my assumption correct?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Unfortunately, Boolean.ToString(IFormatProvider) does not help here:
In any case, Booleans represent True and False, not Yes and No. If you want to map True -> Yes and False -> No, you will have to do that (including localization) yourself; there's no built-in support in the framework for that. Your propopsed solution (Resources.Yes/No) looks fine to me.
The framework itself does not provide this for you (as far as I know). Translating
true/false
intoyes/no
does not strike me as more common than other potential translations (such ason/off
,checked/unchecked
,read-only/read-write
or whatever).I imagine that the easiest way to encapsulate the behavior is to make an extension method that wraps the construct that you suggest yourself in your question:
Usage:
As the other answers indicate, the framework does not allow boolean values to have custom formatters. However, it does allow for numbers to have custom formats. The GetHashCode method on the boolean will return 1 for true and 0 for false.
According to MSDN Custom Numeric Format Strings, when there are 3 sections of ";" the specified format will be applied to "positive numbers;negative numbers;zero".
The GetHashCode method can be called on the bool value to return a number so you can use the Custom Numeric Format String to return Yes/No or On/Off or any other set of words the situation calls for.
Here is a sample that returns on/OFF:
returns: