.net ToString() format documentation

后端 未结 5 1438
感情败类
感情败类 2021-02-20 08:06

I saw a code snippet the other day that converts a Boolean value to the corresponding \"Yes\"/\"No\" value:

CDbl(True).ToString(\"Yes;Yes;No\")

相关标签:
5条回答
  • 2021-02-20 08:39

    It's treating it as a Custom Numeric Format String. Specifically, see the part about section separators in the linked page:

    The ';' character is used to separate sections for positive, negative, and zero numbers in the format string. If there are two sections in the custom format string, the leftmost section defines the formatting of positive and zero numbers, while the rightmost section defines the formatting of negative numbers. If there are three sections, the leftmost section defines the formatting of positive numbers, the middle section defines the formatting of negative numbers, and the rightmost section defines the formatting of zero numbers.

    0 讨论(0)
  • 2021-02-20 08:41

    As @Joel Coehoorn and @tvanfosson said, it's using a custom numeric format string. The reason it works is that a boolean value is convertible to a double using the following (essentially):

    public static double ToDouble(bool value)
    {
        return (value ? ((double) 1) : ((double) 0));
    }
    

    So, if value is true, it returns 1 and if value is false it returns 0. At that point, the section mapping rules apply as described by @tvanfosson (and subsequently @Joel Coehoorn).

    0 讨论(0)
  • 2021-02-20 08:49

    Steve-X has the best documentation for String.Format I've seen so far: Steve-X ToString()

    I know you asked for "ToString", but ToString is dependent to the implementation you are calling (i.e. DateTime.ToString(), decimal.ToString...etc).

    If you are really interested in how it works bust open reflector and peruse the code.

    0 讨论(0)
  • 2021-02-20 08:53

    Take a look here and here, for official documentation. And this great cheatsheet from Jhon Sheehan's Blog!

    0 讨论(0)
  • 2021-02-20 08:56

    It's using the literal format string from the customized numeric format strings. You can supply a literal that maps onto numbes that are postive, negative, or zero numbers. The first "yes" maps to positive, the second to negative, and the "no" to zeros. Thus any non-zero is yes, and only zeros are no. This is equivalent to standard true/false semantic interpretations on numeric values.

    Look under "section separator" of the Custom Numeric Format strings page.

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