为什么C#不定义字符的加法运算? [英] Why does C# not define an addition operation for char's?

查看:190
本文介绍了为什么C#不定义字符的加法运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说。 相关的这个问题。

为什么下面的代码不工作?它似乎在逻辑上合理

Why does the following code not work? It seems reasonable logically.

string foo = 'a' + 'b'; // Fails with an invalid int -> string conversion

现在,从上面的链接的问题,我们可以推断出是怎么回事:编译器使用隐式字符 - > INT转换,然后添加这些值。这使我相信,绝不能成为字符已定义的加法运算!这是真的,如果是这样,为什么会出现无

Now, from the above linked question we can infer what is going on here: the compiler is using the implicit char -> int conversion, then adding those values. This leads me to believe that there mustn't be an addition operation defined for chars! Is this true, and if so, why is there none?

编辑:普遍的共识是,它是没有这么多,有没有一个限定这么多,因为我期望能够定义一个没有了。

The general consensus is that it isn't so much that there isn't one defined so much as the one that I expect to be defined isn't.

推荐答案

首先,一个字关于你的演绎过程。你扣 - 即字符转换为int,因此没有对焦炭没有定义加法运算符 - 是当场就,你那么好。但我注意到,推导过程是不必要的。你可以简单阅读说明书,这清楚地描述了所有内置的加法运算的7.7.4小节。简单地说,他们是INT + INT,UINT + UINT,长+长,ULONG + ULONG,浮动+浮动,双+双,小数点+小数,枚举和基础类型,委托组合,字符串+字符串,字符串+对象宾语+字符串。 (当然,这些的提升对空的版本涉及的价值类型。)所以,是的,没有加法运算内搭个字符。

First off, a word about your deductive process. Your deduction -- that char is converted to int, and therefore there is no addition operator defined on char -- is spot on, so good on you. But I note that the deduction process was unnecessary. You could have simply read section 7.7.4 of the specification, which clearly describes all the built-in addition operators. Briefly, they are int + int, uint + uint, long + long, ulong + ulong, float + float, double + double, decimal + decimal, enum-and-underlying type, delegate combination, string + string, string + object and object + string. (And of course, the lifted-to-nullable versions of those that involve value types.) So yes, there are no addition operators which take chars.

二,回答你:为什么不呢? - 字符是有点怪。他们的存储是短整型的,但它们的语义是那些在字符串中的字符的。所以应一个字符被视为它的整数形式,或为短字符串?语言设计者在这种情况下,决定按照类似C语言较早的铅和治疗一样的字符做整型对他们的数学,不涉及字符串时。如果要像对待短字符串,有许多方法来字符转换为字符串。追加空字符串,作为另一个答案建议,明确地告诉编译器这个操作对字符串,而不是人物的整数值。

Second, to answer your "why not?" -- chars are a bit weird. Their storage is that of short integers, but their semantics are those of the characters in a string. So should a char be treated as its integer form, or as a short string? The language designers decided in this case to follow the lead of earlier languages like C and treat chars like integers when doing mathematics on them that does not involve strings. If you want to treat them like short strings, there are any number of ways to convert chars to strings. Appending the empty string, as another answer suggests, unambiguously tells the compiler "this operation is on strings, not on the character's integer value".

这篇关于为什么C#不定义字符的加法运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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