[英]Declaring a string from a character has an unexpected result. Why is this so?
找了半天這個bug。 為什么第三種情況會出現意想不到的結果?
// 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
這是操作的順序,在所有其他示例中,您將字符添加到字符串中。 但是,在第三個示例中,您將一個字符添加到一個字符中,該字符充當一個字節並進行整數乘法。
然后將整數添加到字符串“A”中
所以 'a' + 'a' = 194 和 194 + "A" = 197A
這就是你看到的結果
您正在混合字符和字符串。 這: 'a' + 'a' 導致 ascii 字符值的整數加法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.