.net ToString() format documentation

2020-07-05 05:58发布

问题:

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")

The code works fine but I'm curious how it works and I haven't been able to find the answer in the MSDN documentation for ToString().

Can anybody shed some light on this?

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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).



回答5:

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.



标签: .net vb.net