开发者

Adding two functions?

开发者 https://www.devze.com 2023-02-09 09:02 出处:网络
I just browsed through \"C# in Depth\" and stumbled upon the following code: Func<string> stringFunc = () => \"\";

I just browsed through "C# in Depth" and stumbled upon the following code:

Func<string> stringFunc = () => "";
Func<object> objectFunc = () => new object();
Func<object> combined = objectFunc + stringFunc;

I'm pretty sure that adding two functions is meaningless in mathematics, so why would any programmer want an overload of the binary operator+ for functions? This seems to be a perfect example of why overloading operators can do harm开发者_开发知识库 (and I generally support the idea of operator overloading).

  1. What does it mean to add two functions in C#? (I'm a C# noob, so bear with me.)

  2. Do you agree that it was a design mistake to overload operator+ here?

  3. What would be a better syntactic to achieve whatever it is operator+ does here?


Writing delegate1 + delegate2 will create a third delegate instance which combines the first two, calling all functions in both delegates.
It's primarily intended for events.

Documentation


Adding two functions is perfectly meaningful in mathematics. When you take the view that functions are operators then the space of all such operators is a linear space (under certain conditions). This is a very productive standpoint that yields a lot of useful mathematical insight.

Of course, that's not what's happening here, but I wanted to put you right on the mathematical side of your question!

0

精彩评论

暂无评论...
验证码 换一张
取 消