gpt4 book ai didi

c# - 字符 + 字符 = 整数?为什么?

转载 作者:IT王子 更新时间:2023-10-29 03:44:20 25 4
gpt4 key购买 nike

为什么在 C# 中添加两个 char 结果是 int 类型?

例如,当我这样做时:

var pr = 'R' + 'G' + 'B' + 'Y' + 'P';

pr 变量变为 int 类型。我希望它是 string 类型,值为 "RGBYP"

C#为什么要这样设计?添加两个 char 的默认实现不应该生成连接 charstring,而不是 int?

最佳答案

根据the documentation of char它可以隐式转换为整数值。 char 类型未定义自定义 operator +,因此使用整数。

Eric Lippert 在他的 blog entry on "Why does char convert implicitly to ushort but not vice versa?" 中的第一条评论中很好地解释了没有隐式转换为字符串的基本原理。 :

It was considered in v1.0. The language design notes from June 6th1999 say "We discussed whether such a conversion should exist, anddecided that it would be odd to provide a third way to do thisconversion. [The language] already supports both c.ToString() and newString(c)".

(记入 JimmiThfinding that quote )

关于c# - 字符 + 字符 = 整数?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16851809/

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