[英]In c# why (char)(1) + (char)(2) results in int 3
I am trying to covert some VB.NET code to C# and found this interesting thing. 我试图将一些VB.NET代码转换为C#并发现这个有趣的事情。 Adding two chars returns different results in VB.NET and C#.
添加两个字符会在VB.NET和C#中返回不同的结果。
VB.NET - returns string VB.NET - 返回字符串
Chr(1) & Chr(2) = " "
C# - returns int C# - 返回int
(char)(1) + char(2) = 3
How can i add(concatenate) two chars in C#? 如何在C#中添加(连接)两个字符?
In C# char
is a 16-bit numeric type , so +
means addition, not concatenation. 在C#中,
char
是一个16位数字类型 ,因此+
表示加法,而不是连接。 Therefore, when you add a
and b
you get a+b
. 因此,当你添加
a
和b
你得到a+b
。 Moreover, the result of this addition is an int
( see a quick demo ). 此外,这个添加的结果是一个
int
( 参见快速演示 )。
If by "adding two characters" you mean "concatenation", converting them to a strings before applying operator +
would be one option. 如果通过“添加两个字符”表示“连接”,则在应用operator
+
之前将它们转换为字符串将是一种选择。 Another option would be using string.Format
, like this: 另一种选择是使用
string.Format
,如下所示:
string res = string.Format("{0}{1}", charA, charB);
By adding to an empty string you can force the "conversion" of char
to string
... So 通过添加到空字符串,您可以强制将
char
转换为string
......所以
string res = "" + (char)65 + (char)66; // AB
(technically it isn't a conversion. The compiler knows that when you add to a string
it has to do some magic... If you try adding null
to a string, it consider the null
to be an empty string, if you try adding a string
it does a string.Concat
and if you try adding anything else it does a .ToString()
on the non-string member and then string.Concat
) (从技术上讲,它不是转换。编译器知道当你添加到
string
它必须做一些魔术......如果你尝试将null
添加到字符串,它会认为null
是一个空字符串,如果你尝试添加一个string
它会做一个string.Concat
,如果你尝试添加其他任何东西,它会在非字符串成员上执行.ToString()
,然后是string.Concat
)
The best answer is in the comments so I want elevate it here to a proper answer. 最好的答案是在评论中,所以我想在这里提出一个正确的答案。 With full credit going to @Jeow Li Huan:
完全信用@Jeow Li Huan:
string res = string.Concat(charA, charB);
(char)(1) has an ascii value of 1 and (char)(2) ascii value of 2 (char)(1)的ascii值为1,(char)(2)的ascii值为2
so ascii value of 1 + 2 (ie (char)1 + (char)2 ) will be equal to 3. 所以ascii值为1 + 2(即(char)1 +(char)2)将等于3。
if you do: "2" + "1" this will give you "21" (althou you should not use this to join strings, bad practice) 如果你这样做:“2”+“1”这将给你“21”(你不应该用它来加入字符串,不好的做法)
if you do: '2' + '1' this will give you int value of 99 that is ascii value of 2 (which is 50) + ascii value of 1(which is 49). 如果你这样做:'2'+'1'这将给你int值99,即ascii值为2(即50)+ ascii值为1(即49)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.