gpt4 book ai didi

c# - 将 char 与 int 和 string 连接起来会产生奇怪的结果

转载 作者:行者123 更新时间:2023-12-03 19:38:14 35 4
gpt4 key购买 nike

我正在编码,需要建立一个文件名。我想用 _ 分隔文件名的各个部分。

我想既然我只想添加 char in 我可以使用 '_'

int id = 125;

string testWithChar = id + '_' + "Something";
Console.WriteLine(testWithChar);

但是当我这样做时,我得到了这个:

220Something

有点奇怪。

但是如果我做对了:

int id = 125;

string testWithString = id + "_" + "Something";
Console.WriteLine(testWithString);

我得到了预期的输出:

125_Something

但我很好奇。第一个给我不同号码的到底发生了什么?

最佳答案

原因是,C# 将 char 视为 unicode 值,因此它们之间的加法不是字符串相加,而是整数相加。_ 在 ascii 中是 95,因此

int id = 125;

string testWithChar = id + '_' + "Something";

相当于:

string testWithChar = 125 + 95 + "Something";

相反,当您添加“_”时,加法是在字符串和整数之间完成的 - 并且运算符只是将字符串附加到它。

关于c# - 将 char 与 int 和 string 连接起来会产生奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32019018/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com