Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2011-06-02
Extension methods is a well known concept in C#. The idea is that you can add methods to a type without inheritance, as described here.
Visual Basic doesn’t have any linguistic support for extension methods, but it can be done thanks to a method attribute. There are some rules for doing this. You must declare your sub or function in a standard module, not a class. You must have at least one parameter, and that parameter is the type you are extending. Any other parameters will be parameters in your function. Finally, your sub or function must have the System.Runtime.CompilerServices.Extension attribute.
So if you want to add a function that takes no parameters to the Integer type, you will have to define a function that takes one parameter, an Integer. If you want to add a function that takes one parameter, you will have to define a function that takes two parameter, the first must be an Integer and the second (who will serve as the first parameter in your function) can be of any type you like.
Public Function DoubleValue(ByVal I As Integer) As Integer Return I * 2 End Function
Remember, the code must be written in a standard module.
The last thing that you have to do, is to add the attribute.
<System.Runtime.CompilerServices.Extension()> Public Function DoubleValue(ByVal I As Integer) As Integer Return I * 2 End Function
(The above code is VBx syntax. For older Visual Basic versions, add a blank followed by an underscore to the attribute line.)
Now you can call the DoubleValue function from any Integer, in this case 5:
Console.WriteLine(5.DoubleValue())
The output will of course be 10.
Categories: VB.NET
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply