How to generically format a boolean to a Yes/No st

2019-01-11 15:52发布

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?

3条回答
【Aperson】
2楼-- · 2019-01-11 16:41

Unfortunately, Boolean.ToString(IFormatProvider) does not help here:

The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.

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.

查看更多
爷的心禁止访问
3楼-- · 2019-01-11 16:45

The framework itself does not provide this for you (as far as I know). Translating true/false into yes/no does not strike me as more common than other potential translations (such as on/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:

public static class BooleanExtensions
{
    public static string ToYesNoString(this bool value)
    {
        return value ? Resources.Yes : Resources.No;
    }
}

Usage:

bool someValue = GetSomeValue();
Console.WriteLine(someValue.ToYesNoString());
查看更多
仙女界的扛把子
4楼-- · 2019-01-11 16:45

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:

var truth   = string.Format("{0:on;0;OFF}", true.GetHashCode());
var unTruth = string.Format("{0:on;0;OFF}", false.GetHashCode());

returns:

truth   = on
unTruth = OFF
查看更多
登录 后发表回答