Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

c# - How EXACTLY can += and -= operators be interpreted?

What exactly (under the hood) do the += and -= operators do?

Or are they implicit in that they are defined per type?

I've used them extensively, it's a very simple feature of the syntax, but I've never thought about the depths of how it works.

What Brought About the Question

I can concatenate a string value like so:

var myString = "hello ";
myString += "world";

All fine. But why doesn't this work with collections?

var myCol = new List<string>();
myCol += "hi";

You may say 'well you're attempting to append a different type, you can't append a string to a type that isn't string'. But the following doesn't work either:

var myCol = new List<string>();
myCol += new List<string>() { "hi" };

Ok, maybe it doesn't work with collections, but is the following not a (kind of) collection of event handlers?

myButton.Click += myButton_Click;

I'm obviously lacking an in-depth understanding of how these operators work.

Please note: I'm not trying to build the collection myCol in this way, in a real project. I'm merely curious about the workings of this operator, it's hypothetical.

question from:https://stackoverflow.com/questions/40503509/how-exactly-can-and-operators-be-interpreted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The += operator is implicitly defined like this: a += b turns into a = a + b;, same with the -= operator.
(caveat: as Jeppe pointed out, if a is an expression, it is only evaluated once if you use a+=b, but twice with a=a+b)

You cannot overload the += and -= operator separately. Any type that supports the + operator also supports +=. You can add support for += and -=to your own types by overloading + and -.

There is however one exception hard coded into c#, which you have discovered:
Events have a += and -= operator, which adds and removes an event handler to the list of subscribed event handlers. Despite this, they do not support the + and - operators.
This is not something you can do for your own classes with regular operator overloading.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...