VB.NET 为什么要这样声明这个子例程?
VB.NET 2010,.NET 4
我有一个基本问题:我在网上找到了一个子例程,如此声明:
Public Sub MyFunction(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of T)) ...
我想知道声明的 (Of T As Control) 部分潜艇的名字。我看到 T 稍后用于指定 Control 的类型和 Action(Of T) 中,但为什么这样做而不是仅仅这样做:
Public Sub MyFunction(ByVal Control As Control, ByVal Action As Action(Of Control)) ...
子名称后面的部分是什么意思?它的目的是什么?非常感谢,并对我的无知感到抱歉。
VB.NET 2010, .NET 4
I have a basic question: I have a subroutine that I found somewhere online declared thusly:
Public Sub MyFunction(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of T)) ...
I'm wondering about the (Of T As Control) part of the declaration after the sub's name. I see that T is used later in specifying the type of Control and in Action(Of T), but why is it done this way instead of just doing:
Public Sub MyFunction(ByVal Control As Control, ByVal Action As Action(Of Control)) ...
What does that part after the sub's name mean? What is its purpose? Thanks a lot and sorry for my ignorance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是 VB.NET 的 通用方法 声明语法:
That is VB.NET's generic method declaration syntax:
(Of T) 是泛型类型参数,添加 As Control 会约束 T 的类型从 Control 继承。您可以用第二种方式编写该方法,但最终可能必须将 Control 强制转换为任何继承的类型(在 Action 中的 lambda 表达式中或在 MyFunction 主体中)。泛型可以让你避免这种情况。
例如:
在简单的情况下它看起来不太有价值,但对于更复杂的情况来说它的价值是无价的。
(Of T) is a generic type parameter, adding As Control constrains the type of T to inherit from Control. You could write the method the second way, but you'd probably end up having to cast the Control to whatever inherited type, within the lambda expression in the Action, or in the body of MyFunction. Generics allow you to avoid that.
For example:
It doesn't look too valuable in trivial cases, but it's invaluable for more complex cases.
正如其他人所说,它是一个受约束的通用参数。但还没有人回答你问题的这一部分:
答案就在行动中。如果它只是声明为 Control,您将无法执行类似的操作,因为并非所有控件都有 .Text 属性*:
函数的主体只需要知道它是处理某种类型的控件,但传递给函数的 Action(Of T) 可能想知道控件的实际类型。
是的,所有控件都有 .Text 属性。让我们假装有些人没有这样做
As others have said, it's a constrained generic parameter. But no one has yet addressed this part of your question:
The answer is in the action. If it were just declared as a Control, you wouldn't be able to do something like this, because not all controls have a .Text property*:
The body of the function just needs to know that it's working on a control of some kind, but the Action(Of T) you pass to the function might want to know the actual type of the control.
Yes, all controls do have a .Text property. Let's pretend for a moment that some didn't