在C#为什么(字符)(1)+(字符)(2)INT 3结果字符、结果、INT

2023-09-03 16:40:52 作者:倾心不倾城

我想隐蔽一些VB.NET code到C#,发现这个有趣的事。 增加两个字符返回VB.NET和C#不同的结果。

I am trying to covert some VB.NET code to C# and found this interesting thing. Adding two chars returns different results in VB.NET and C#.

VB.NET - 返回字符串的

Chr(1) & Chr(2) = "  "

C# - 返回INT 的

(char)(1) + char(2) = 3

我如何添加(串连)用C#两个字符?

How can i add(concatenate) two chars in C#?

推荐答案

在C#中 字符是一个16位的数字类型,所以 + 意味着另外,不串联。因此,当您添加 A B A + B 。此外,这种加法的结果是 INT (看到一个快速演示)。

In C# char is a 16-bit numeric type, so + means addition, not concatenation. Therefore, when you add a and b you get a+b. Moreover, the result of this addition is an int (see a quick demo).

如果通过增加两个字符你的意思是串联,将它们转换为字符串应用运营商之前 + 将是一个选项。另一种办法是使用的String.Format ,像这样的:

If by "adding two characters" you mean "concatenation", converting them to a strings before applying operator + would be one option. Another option would be using string.Format, like this:

string res = string.Format("{0}{1}", charA, charB);