在 c# 为什么 (char)(1) + (char)(2) 导致 int 3

3

本文介绍了在 c# 为什么 (char)(1) + (char)(2) 导致 int 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试将一些 VB.NET 代码转换为 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# - 返回整数

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

如何在 C# 中添加(连接)两个字符?

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

推荐答案

在 C# 中 char 是 16 位数字类型,所以 + 表示加法,而不是串联.因此,当您添加 ab 时,您会得到 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# 为什么 (char)(1) + (char)(2) 导致 int 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14