本文介绍了为什么微软不为过载StringBuilder的+ =运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关StringBuilder类,为什么不超载+ =运算符,而不是采用独特的.Append()方法?

For the StringBuilder class, why not overload the += operator instead of a using a unique .Append() method?

追加()只连接字符串为什么他们不只是重载+ =运算符,像这样:

Append() only concatenates strings so why did they not just overload += operator like so:

StringBuilder sb = new StringBuilder();
sb += "My string";



它是效率的情况?
是它公约或直观的情况?

Is it a case of efficiency?Is it a case of convention or intuitiveness?

谢谢,

推荐答案

算术运算应仅限于像算术值类型。这已经够糟糕了两个字符串的总和是第三个字符串。与混为一谈字符串连接的加法运算是一个值得商榷的选择,因为字符串连接服从极少数的另外的规则;尤其是, A + B!= B + A

Arithmetical operations should be limited to types that act like arithmetical values. It is bad enough that the sum of two strings is a third string. Conflating the addition operation with string concatenation is a questionable choice because string concatenation obeys very few of the rules of addition; in particular, a + b != b + a.

但去那里字符串的建设者的 - 这被定义的可变状态的而不是算术值的 - 是的可怕的两件事情的总和应该是从两个加数不同,第三事情。的即 A + = B 必须具有相同的语义为 A = A + b ,而不是 a.MutateWith(b)如果没有赋值 A 末则复合赋值是错误的运营商。

But to go there for string builders -- which are by definition mutable state and not arithmetical values -- is horrid. The sum of two things should be a third thing that differs from the two summands. That is, a += b must have the same semantics as a = a + b and not a.MutateWith(b). If there isn't an assignment to a at the end then compound assignment is the wrong operator.

更一般为从不矫揉造作的运算符重载。运算符重载在那里,这样就可以让两个复数添加到第三,不这样就可以使一个客户加花生酱一罐等于采购订单,或一些这样的愚蠢。

More generally: never make cutesy operator overloads. Operator overloads are there so that you can make two complex numbers add to a third, not so that you can make an customer plus a jar of peanut butter equal a purchase order, or some such silliness.

这篇关于为什么微软不为过载StringBuilder的+ =运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:31