简体   繁体   English

为什么C#没有为char定义加法运算?

[英]Why does C# not define an addition operation for char's?

As the title says. 如标题所示。 Related to this question. 与这个问题有关。

Why does the following code not work? 为什么以下代码不起作用? It seems reasonable logically. 从逻辑上讲,这似乎是合理的。

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

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. 现在,从上述链接的问题中,我们可以推断出发生了什么:编译器正在使用隐式char-> int转换,然后添加这些值。 This leads me to believe that there mustn't be an addition operation defined for char s! 这使我相信,一定不能为char定义加法运算! Is this true, and if so, why is there none? 这是真的吗?如果是这样,为什么没有呢?

EDIT: 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. 编辑:普遍的共识是,没有太多的定义,而我希望没有定义的定义太多。

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. 您的推论-即char转换为int,因此char上没有定义加法运算符-很容易理解,对您来说很好。 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. 您可能只需要阅读规范的7.7.4节,即可清楚地描述所有内置的加法运算符。 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. 简而言之,它们是int + int,uint + uint,long + long,ulong + ulong,float + float,double + double,decimal + decimal,枚举和基础类型,委托组合,string + string,string + object和对象+字符串。 (And of course, the lifted-to-nullable versions of those that involve value types.) So yes, there are no addition operators which take chars. (当然,涉及值类型的那些类型的提升为可空版本。)是的,没有使用char的加法运算符。

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? 那么应将char视为其整数形式还是一个短字符串? 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. 在这种情况下,语言设计人员决定遵循诸如C之类的早期语言,在对不涉及字符串的数学运算时将char视为整数。 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". 另一个答案表明,在空字符串后面附加一个明确的内容告诉编译器“此操作是在字符串上,而不是在字符的整数值上”。

What you are really looking for is this: 您真正要寻找的是:

string foo = String.Concat('a', 'b');

Which is what the compiler does with the '+' operator on strings anyways. 无论如何,编译器对字符串使用'+'运算符。

This is about twice as fast as any String.Format operation. 这大约是任何String.Format操作的两倍。

I'm thinking one should focus on the word "why" in your question. 我想一个人应该关注您问题中的“为什么”一词。 In C#, the behavior of adding two characters has been defined to mean "add the Unicode values" rather than "concatenate". 在C#中,添加两个字符的行为已定义为表示“添加Unicode值”而不是“连接”。 We are in agreement this this could have been more reasonably defined to mean "concatenate" given that strings and chars are much more distinct entities from integers than they were in past lives (eg, The C Programming Language). 我们一致认为,考虑到字符串和字符与整数相比,它们比前一辈子(例如,C编程语言)具有更大的区别性,因此可以更合理地将其定义为“连接”。

'a' is a character constant. “ a”是字符常量。 Traditionally, a character constant, at least in C, was just another way to represent an integer. 传统上,至少在C语言中,字符常量只是表示整数的另一种方式。 In this case, the Unicode value of said integer ('a' = 97, 'b' = 98, etc.). 在这种情况下,所述整数的Unicode值(“ a” = 97,“ b” = 98,依此类推)。 Hence, the expression 'a' + 'b' is taken to mean add those two Unicode values together. 因此,表达式“ a” +“ b”用来表示将这两个Unicode值相加。

To achieve what you're expecting, do 要实现您的期望,请执行

String foo = "a" + "b";  // double quotes = single-character strings to concatenate

As has already been said, char is considered a form of integer rather than a string, so fundamentally an addition operation is adding two numbers, rather than performing concatenation. 正如已经说过的,char被认为是整数而不是字符串的形式,因此从根本上说,加法运算是将两个数字相加,而不是执行串联。 You can get two characters into a string like this: 您可以将两个字符放入字符串中,如下所示:

string str = String.Format("{0}{1}", 'a', 'b');

To get your chars to "add" up you could do one of several things similar to your original intent: 为了使字符“累加”,您可以做一些与您的原始意图类似的事情:

string foo2 = 'a' + "" + 'b'; //  Succeeds
string foo3 = 'a'.ToString() + 'b'.ToString(); // Succeeds
string foo4 = string.Concat('a', 'b'); // Succeeds

For the foo2 example you give the compiler a clue by dropping in an empty string and force an implicit char to string conversion for each char individually. 对于foo2示例,您可以通过插入空字符串为编译器提供线索,并分别为每个char强制将隐式char转换为字符串。

For the foo3 example you use the ToString call on each character to allow the addition of two strings. 对于foo3示例,您在每个字符上使用ToString调用以允许添加两个字符串。

You could use overload of addition operator for string and try this: 您可以对字符串使用加法运算符的重载,然后尝试以下操作:

var result = "" + 'a' + 'b';

but please don't confuse with 但请不要与

var result = 'a' + 'b' + "";  // BAD !!!!!

as it will give you int converted to string and equal to "195". 因为它将给您int转换为字符串并等于“ 195”。

The idea is to have overload of operator + for string to kick in and you should have first argument as string to achieve this. 这个想法是让运算符+重载以插入字符串,并且您应该将第一个参数作为字符串来实现。

It looks a bit like cheating but that's C# - senseless and merciless! 看起来有点像作弊,但这就是C#-毫无意义和残酷! (actually it's .Net which doesn't have operator + overload for (Char, Char) and C# trying to cast Char to Int32). (实际上是.Net,它没有运算符+(Char,Char)和C#试图将Char强制转换为Int32的重载)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM