简体   繁体   English

从字符声明字符串会产生意外结果。 为什么会这样?

[英]Declaring a string from a character has an unexpected result. Why is this so?

Half a day looking for this bug.找了半天这个bug。 Why is there an unexpected result in the third case?为什么第三种情况会出现意想不到的结果?

        // case 1
        string value1 = "a" + "a" + "A";  
        byte[] asciiBytes1 = Encoding.ASCII.GetBytes(value1); // expected: 97 - 97 - 65
        Console.WriteLine(string.Join(" - ", asciiBytes1));   //   result: 97 - 97 - 65

        // case 2
        string value21 = 'a' + "A"; 
        byte[] asciiBytes21 = Encoding.ASCII.GetBytes(value21); // expected: 97 - 65
        Console.WriteLine(string.Join(" - ", asciiBytes21));    //   result: 97 - 65 

        // case 3
        string value22 = 'a' + 'a' + "A"; 
        byte[] asciiBytes22 = Encoding.ASCII.GetBytes(value22); // expected: 97 - 97 - 65
        Console.WriteLine(string.Join(" - ", asciiBytes22));    //   result: 49 - 57 - 52 - 65

It's the order of operations, In all of the other examples you add a char to a string.这是操作的顺序,在所有其他示例中,您将字符添加到字符串中。 However in the third example you add a char to a char, which acts as a byte and does integer multiplication.但是,在第三个示例中,您将一个字符添加到一个字符中,该字符充当一个字节并进行整数乘法。

And then it integer is added to the string "A"然后将整数添加到字符串“A”中

so 'a' + 'a' = 194 and 194 + "A" = 197A所以 'a' + 'a' = 194 和 194 + "A" = 197A

and thats the results you are seeing这就是你看到的结果

You are mixing chars and strings.您正在混合字符和字符串。 This: 'a' + 'a' results in the integer addition of the ascii char values.这: 'a' + 'a' 导致 ascii 字符值的整数加法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM