How to generically format a boolean to a Yes/No string?

一个人想着一个人 提交于 2019-11-27 04:44:16

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());

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!