C# 委托函数
我遇到了一行我似乎无法理解的代码
让我解释一下。
我所理解的是,通过下面的行,我定义了一种名为“myDelegate”的委托类型。该类型可以保存指向具有签名 int (int, int) 的函数的指针,
public delegate int myDelegate(int a, int b);
但我没有得到以下行:
public delegate T Func<T>(T a, T b);
我的意思是为什么我要定义一个名为 Func 的类型,它已经在 .NET 框架中定义了?
I came across a line of code that i can't seem to grasp
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,当框架中存在具有相同名称和数量的泛型类型参数的委托时,声明自己的委托似乎是一个坏主意 - 但它并不是无效。我建议,如果这是您拥有的代码,请适当地重命名它。请注意,它与
Func
不同,因为它使用T
作为输入和输出。您可能想将其称为BinaryOperator
或类似的名称(尽管二元运算符不必具有相同的操作数类型,返回值也不必具有相同的类型)。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 usingT
for both inputs and the output. You might want to call itBinaryOperator
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)..NET
Func
有所不同:委托定义并没有错,只是命名会与 .NET 版本混淆。
The .NET
Func<T>
is different:The delegate definition is not wrong, it's the naming that will get confusing with the .NET version.
Func 语法是为了方便起见,通常最好对它们提供的内容进行标准化(恕我直言)。
Func 和 Action 既方便又容易记住。相比之下,我发现委托语法有点笨拙。
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.