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

前端 未结 4 1347
萌比男神i
萌比男神i 2020-11-30 09:53

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?
I

4条回答
  •  被撕碎了的回忆
    2020-11-30 10:07

    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
    

提交回复
热议问题