[英]What is the VB.NET equivalent of passing 'this' in a method signature in C#.NET?
My question stems from the code samples from Wrox Press's Professional ASP.NET Design Patterns. 我的问题来自Wrox Press的Professional ASP.NET Design Patterns的代码示例。 The code downloads are in C#, however, I'm working through the samples in VB. 代码下载在C#中,但是,我正在VB中研究示例。
I would appreciate if someone could explain what 'this' means in the following method signature, and what the equivalent method signature would be in VB.NET. 如果有人可以解释以下方法签名中的“ this”是什么意思,以及VB.NET中的等效方法签名,我将不胜感激。
Here is the code sample (from p.51) in question: 这是有问题的代码示例(来自p.51):
public static void Apply(this IList<Product> products, IDiscountStrategy discountStrategy) { ... }
This is an extension method they are implemented in VB.NET 这是它们在VB.NET中实现的扩展方法
The syntax you need is: 您需要的语法是:
<Extension()>
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
for example 例如
This is an extension method. 这是一种扩展方法。 The this indicates that you can call the static method with the following syntax: 这表明您可以使用以下语法调用静态方法:
products.Apply(strategy);
as opposed to to 相对于
WhateverClass.Apply(products, strategy);
In VB you would decorate the method with the Extension
attribute 在VB中,您可以使用Extension
属性装饰该方法
<Extension()>
Sub Apply(ByVal products as IList<Product>, ByVal discountStrategy as IStrategy)
...
See http://msdn.microsoft.com/en-us/library/bb384936.aspx for more 有关更多信息,请参见http://msdn.microsoft.com/en-us/library/bb384936.aspx
For an extension method in VB you use the ExtensionAttribute
对于VB中的扩展方法,请使用ExtensionAttribute
<Extension()>
Public Sub Apply(IList(of Product) products, IDiscountStrategy discountStrategy)
'...
End Sub
The above syntax may not be 100% 上面的语法可能不是100%
I think it's for extension methods. 我认为这是用于扩展方法。 Not sure how those are implemented in VB.NET. 不知道这些如何在VB.NET中实现。
the this
used thusly denotes an extension method. 因此, this
表示扩展方法。 you now have an Apply
method that can be used on any IList<Product>
as if it were a member method, so you can call it like 您现在有了一个Apply
方法,该方法可以在任何IList<Product>
,就像它是成员方法一样,因此您可以像这样调用它
list.Apply(discountStrategy);
instead of like 而不是像
Apply(list, discountStrategy);
Its really useful to avoid having to name that method ApplyDiscountStrategyToListOfProducts
, and having tons of Apply*ToListOf*
methods. 避免必须将该方法ApplyDiscountStrategyToListOfProducts
,并具有大量Apply*ToListOf*
方法,这确实很有用。
The VB equivalent is here: http://msdn.microsoft.com/en-us/library/bb384936.aspx VB等效项在这里: http : //msdn.microsoft.com/en-us/library/bb384936.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.