My question stems from the code samples from Wrox Press's Professional ASP.NET Design Patterns. The code downloads are in C#, however, I'm working through the samples in 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.
Here is the code sample (from p.51) in question:
public static void Apply(this IList<Product> products, IDiscountStrategy discountStrategy) { ... }
This is an extension method they are implemented in 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
<Extension()>
Sub Apply(ByVal products as IList<Product>, ByVal discountStrategy as IStrategy)
...
See http://msdn.microsoft.com/en-us/library/bb384936.aspx for more
For an extension method in VB you use the ExtensionAttribute
<Extension()>
Public Sub Apply(IList(of Product) products, IDiscountStrategy discountStrategy)
'...
End Sub
The above syntax may not be 100%
I think it's for extension methods. Not sure how those are implemented in VB.NET.
the this
used thusly denotes an extension method. 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
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.
The VB equivalent is here: http://msdn.microsoft.com/en-us/library/bb384936.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.