问题
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