How is null + true a string?

前端 未结 7 676
后悔当初
后悔当初 2021-01-30 05:49

Since true is not a string type, how is null + true a string ?

string s = true;  //Cannot implicitly convert type \'bool\' to \'string\         


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 06:48

    Interestingly, using Reflector to inspect what is generated, the following code:

    string b = null + true;
    Console.WriteLine(b);
    

    is transformed into this by the compiler:

    Console.WriteLine(true);
    

    The reasoning behind this "optimization" is a bit weird I must say, and does not rhyme with the operator selection I would expect.

    Also, the following code:

    var b = null + true; 
    var sb = new StringBuilder(b);
    

    is transformed into

    string b = true; 
    StringBuilder sb = new StringBuilder(b);
    

    where string b = true; is actually not accepted by the compiler.

提交回复
热议问题