在C#为什么(字符)(1)+(字符)(2)INT 3结果 [英] In c# why (char)(1) + (char)(2) results in int 3

查看:270
本文介绍了在C#为什么(字符)(1)+(字符)(2)INT 3结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想隐蔽一些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);

这篇关于在C#为什么(字符)(1)+(字符)(2)INT 3结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆