C# 委托函数

发布于 2024-11-26 07:37:27 字数 336 浏览 1 评论 0原文

我遇到了一行我似乎无法理解的代码

让我解释一下。

我所理解的是,通过下面的行,我定义了一种名为“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人事已非 2024-12-03 07:37:27

好吧,当框架中存在具有相同名称和数量的泛型类型参数的委托时,声明自己的委托似乎是一个坏主意 - 但它并不是无效。我建议,如果这是您拥有的代码,请适当地重命名它。请注意,它与 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 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).

时光倒影 2024-12-03 07:37:27

.NET Func 有所不同:

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

委托定义并没有错,只是命名会与 .NET 版本混淆。

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.

听你说爱我 2024-12-03 07:37:27

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文