Is there such thing as a “=+” operator? [closed]

烂漫一生 提交于 2019-12-13 23:21:08

问题


I'm wondering why is += valid but =+ is not valid. Let's say I have code like this:

string strOne = "World!";
strOne =+ "Hello ";//strOne = "Hello " + strOne; not valid
//Error: Operator '+' cannot be applied to operand of type 'string'
//Intended Output: Hello World!

string strTwo = "Hello ";
strTwo += "World!";//strTwo = strTwo + "World!"; valid
//Output: Hello World!

I'm also not sure whether strOne =+ "Hello "; is same as strOne = "Hello " + strOne;. Are there any rules on why =+ is not valid or cannot be syntactically correct?


回答1:


The simple answer is no, there is not a =+ operator. You would have to do

strTwo = "Hello " + strTwo;

Part of the reason that there isn't could be that + is a valid unary operator for number types.

var intValue = +2; 



回答2:


It nothing to do with rules or syntactical correctess in principle, but it concerns the fact that that operator does not exist in the C# language.

Anyway, I would suggest never using + or += operators with strings. It's a bad habit that can chew up memory if strewn throughout an application.

Use string.Concat or string.Format instead, for example. Or StringBuilder for large string operations.



来源:https://stackoverflow.com/questions/31184535/is-there-such-thing-as-a-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!