开发者

C# delegate Func

开发者 https://www.devze.com 2023-03-23 10:01 出处:网络
I came across a line of code that i can\'t seem to grasp 开发者_JAVA百科Let me explain a little. What i do understand is that with the following line i am defining a type of delegate with the name \

I came across a line of code that i can't seem to grasp

开发者_JAVA百科

Let me explain a little.

What i do understand is that with the following line i am defining a type of delegate with the name "myDelegate". This type can hold a pointer to a function with signature int (int, int)

public delegate int myDelegate(int a, int b);

What i do not get is the following line:

public delegate T Func<T>(T a, T b);

I mean why would i define a type called Func which is already defined in the .NET framework ?


Well, it certainly seems like a bad idea to declare your own delegate when one with the same name and number of generic type parameters is available in the framework - but it's not invalid. I suggest that if this is code you own, you rename it appropriately. Note that it's not the same as Func<T> as it's using T for both inputs and the output. You might want to call it BinaryOperator or something similar (although binary operators don't have to have the same operand types, nor does the return value have to be of the same type).


The .NET Func<T> is different:

T Func<T>();
T2 Func<T1, T2>(T1 arg);
T3 Func<T1, T2, T3>(T1 arg1, T2 arg2);
.. etc

The delegate definition is not wrong, it's the naming that will get confusing with the .NET version.


the Func syntax is there as a convenience, and often it is better to standardise on what they provide IMHO.

Func and Action are both convenient and easy to remember. By contrast, I find the delegate syntax a little clumsy.

0

精彩评论

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

关注公众号