字符+字符=整数?为什么? [英] char + char = int? Why?
问题描述
为什么在C#结果中将两个 char
添加到 int
类型?
Why is adding two char
in C# results to an int
type?
例如,当我这样做时:
var pr = 'R' + 'G' + 'B' + 'Y' + 'P';
pr
变量变为 int
类型。我希望它是一个 string
类型,其值为 RGBYP
。
the pr
variable becomes an int
type. I expect it to be a string
type with a value of "RGBYP"
.
为什么C#是这样设计的?添加两个 char
的默认实现不是导致将<$ c $串联的 string
的结果吗? c> char s,而不是 int
?
Why is C# designed like this? Wasn't the default implementation of adding two char
s should be resulting to a string
that concatenates the char
s, not int
?
推荐答案
编码为 char文档可以隐式转换为整数值。 char
类型没有定义自定义的 operator +
,因此使用一个整数。
Accoding to the documentation of char it can be implicitly converted into integer values. The char
type doesn't define a custom operator +
so the one for integers is used.
Eric Lippert在他的博客条目为什么char隐式转换为ushort,反之亦然吗? :
The rationale for there being no implicit conversion to string is explained well in the first comment from Eric Lippert in his blog entry on "Why does char convert implicitly to ushort but not vice versa?":
在v1.0中已对此进行了考虑。来自1999年6月6日
的语言设计说明说:我们讨论了是否应该进行这种转换,
决定提供第三种进行
转换的方法很奇怪。语言]已经支持c.ToString()和新的
String(c)。
It was considered in v1.0. The language design notes from June 6th 1999 say "We discussed whether such a conversion should exist, and decided that it would be odd to provide a third way to do this conversion. [The language] already supports both c.ToString() and new String(c)".
(贷方JimmiTh >找到该报价)
(credit to JimmiTh for finding that quote)
这篇关于字符+字符=整数?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!